如何在Java程序中访问mysql数据库中的数据并进行简单的操作

2024-11-06 05:11:51
推荐回答(1个)
回答(1):

/**
* 获取数据库的连接
* @return conn
*/
public static Connection getConnection() throws Exception{
String url = "jdbc:mysql://10.10.35.188:3306/sgjwx";
String user = "opermain";
String psw = "opermain";
Connection conn = null;
PreparedStatement pstm = null;
ResultSet rs = null;
Class.forName("com.mysql.jdbc.Driver");
if(null == conn) {
try {
conn = DriverManager.getConnection(url, user, psw);
} catch (SQLException e) {
System.out.println("获取失败");
throw new RuntimeException(e);
} finally{
closeResources(conn,pstm,rs);
}
}
return conn;
}
/**
* 释放资源
* @param conn
* @param pstmt
* @param rs
*/
public static void closeResources(Connection conn,PreparedStatement pstmt,ResultSet rs) {
if(null != rs) {
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
throw new RuntimeException(e);
} finally {
if(null != pstmt) {
try {
pstmt.close();
} catch (SQLException e) {
e.printStackTrace();
throw new RuntimeException(e);
} finally {
if(null != conn) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
}
}
}
}
}

// //tuserrole执行插入
// try {
// String sql = "insert into sys_userrole(roleid,userid) values (?,?)";
// conn = getConnection();
// conn.setAutoCommit(false);
// PreparedStatement pstmt = (PreparedStatement) conn.prepareStatement(sql,Statement.RETURN_GENERATED_KEYS);//传入参数:Statement.RETURN_GENERATED_KEYS
// pstmt.setInt(1, 5);
// pstmt.setInt(2, sid);
// pstmt.executeUpdate();
// ResultSet rs = pstmt.getGeneratedKeys(); //获取结果
// int a = -1;
// if (rs.next()) {
// a = rs.getInt(1);//取得ID
// }
// System.out.println(a);
// System.out.println("t_userrole执行成功");
// conn.commit();
// } catch (Exception e) {
// e.printStackTrace();
// System.out.println("执行失败");
// }