在开发中,用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;
}
}
其实还是挺简单的,多看看就会了!