java 连接数据库简单操作

在开发中,用java连接数据库是常见的事,这里说两种方式,用sql语言和调用存储过程实现。由于本人老是分不清具体实现,所以记录下来,可随时参考。

 

import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

public class Getaccountidtext {
 private final static String driver="com.microsoft.sqlserver.jdbc.SQLServerDriver";
 
 
 private String url = "jdbc:sqlserver://11.16.105.200:1433;DataBaseName=personal_info"; 
 private final static String user="c";
 private final static String pwd = "123";
 
 Connection connection=null;
 PreparedStatement pts=null;
 
 public List<String> ShowAccountid(){  //此为返回数据库中得到的id号放入列表中
  List<String> account = new ArrayList<String>();
  try {
   Class.forName(driver);
   connection=DriverManager.getConnection(url, user, pwd);
   Statement stat=connection.createStatement();
   String sql="select AccountID from Basic_Info where AccountID != 100000";  //用sql语句直接读表
     
   ResultSet rs=stat.executeQuery(sql);
   while(rs.next()){
     int accountid=rs.getInt("AccountID");
     String accountidStr =  String.valueOf(accountid);
     account.add(accountidStr);
//     System.out.println(accountid);
   }
    rs.close();
    connection.close();
  } catch (ClassNotFoundException e) {
   e.printStackTrace();
  } catch (SQLException e) {
   e.printStackTrace();
  }
  
  
  return account;
  
 }
 
 public String  Insertfans(String id,String friendid) throws Exception{  //  调用存储过程实现
  int outputflag = 0;
  String mess = null;
  try {
   Class.forName(driver);
   connection=DriverManager.getConnection(url, user, pwd);
   String sql="{call InsertAtion(?,?,?,?)}";
   CallableStatement cs=connection.prepareCall(sql);
   //把string 类型转换为int型
   int assidInt=Integer.parseInt(id);
   int friendidInt=Integer.parseInt(friendid);
   cs.setInt(1,assidInt);
   cs.setInt(2, friendidInt);
   
   cs.registerOutParameter(3, java.sql.Types.INTEGER);  //两个输出
   cs.registerOutParameter(4, java.sql.Types.INTEGER);
   cs.execute();
   outputflag=cs.getInt(3);
   cs.close();
   connection.close();
   if (outputflag==1) {
    return mess="成功";
   }if (outputflag==2){
    return mess="Already attion!";
   }
    
   else {
    return mess="失败";
   }
  } catch (Exception e) {
   e.printStackTrace();
  }
  return mess;
  
 }
 
 
 

}

 

其实还是挺简单的,多看看就会了!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值