获取连接
ResourceBundle resource = ResourceBundle.getBundle("config");
//调用静态方法直接获得键值对中值
String url = resource.getString("jdbc.url");//url
String user = resource.getString("jdbc.username");//url
String pwd = resource.getString("jdbc.password");//url
//加载驱动(固定写法)
Class.forName("com.mysql.jdbc.Driver");
//连接成功,数据库对象(固定写法)
Connection connection = DriverManager.getConnection(url, user, pwd);
普通写法
Statement statement = connection.createStatement();
//执行sql语句,返回结果集
String sql="select * from sys_variable";//sql查询语句
int id = 0;
String key = "";
String value = "";
String description = "";
ResultSet resultSet = statement.executeQuery(sql);
while (resultSet.next()){//循环取值
id = resultSet.getInt("id");
key = resultSet.getString("key");
value = resultSet.getString("value");
description = resultSet.getString("description");
SysVariable sysVariable = new SysVariable();
sysVariable.setId(id);
sysVariable.setKey(key);
sysVariable.setValue(value);
sysVariable.setDescription(description);
sysList.add(sysVariable);//将值存入设置好的全局变量中
}
resultSet.close();
statement.close();
connection.close();
防止sql注入写法
PreparedStatement pstmt = connection.prepareStatement("update sendaccbalancelog set " +
"handledate=now(),resultcode=?,resultinfo=? " +
"where regicode=? and accdate=? and accountno=? ");
pstmt.setString(1, retcode);
pstmt.setCharacterStream(2, new java.io.StringReader(retmsg), retmsg.length());
pstmt.setString(3, ""+data.get("regicode"));
pstmt.setString(4, ""+data.get("transDate"));
pstmt.setString(5, ""+data.get("accountNo"));
pstmt.execute();
pstmt.close();
con.commit(); // 提交事务
jdcb调用存储过程
CallableStatement cstmt = connection.prepareCall("{call SP_ZSYW_TRANSINFO_F(?,?,?,?) }");
cstmt.setString(1, billID); //传入参数
cstmt.setString(2, billType); //传出参数
cstmt.registerOutParameter(3, Types.VARCHAR);//传出参数
cstmt.registerOutParameter(4, Types.INTEGER);//传出参数
cstmt.execute();
SP_ZSYW_TRANSINFO_F为存储过程的名称
注意:结束后不要忘记提交事务和关闭各个连接