// Java连接数据库
Connection conn = null;
PreparedStatement stat = null;
Result result = null;
// 如果是Oracle数据库,则是 driver = "oracle.jdbc.OracleDriver";
private String driver = "com.mysql.jdbc.Driver";
// Oracle数据库: url = "jdbc:oracle:thin:@localhost:1521:数据库名";
private String url = "jdbc:mysql://localhost:3306/数据库名";
private String username = "root";
private String password = "root";
/**
* 获取Connection对象
* @return
*/
public Connection initConnection(){
try{
Class.forName(driver);
conn = DriverManager.getConnection(url,username,password);
System.out.println("连接数据库成功");
} catch(ClassNotFoundException e){
throw new RuntimeException("Class not found " + e);
} catch(SQLException e){
throw new RuntimeException("Connection Error! " + e);
}
return conn;
}
/**
*
*/
public void UpdateData(String stuName, int gender, int age, String address) {
conn = initConnection();
String sql = "select id from student where 1 = 1 and stu_name = ?";
String sqlStr = "update student set stu_name=?,gender=?,age=?,address=? where id=?";
int count = 0;
try {
// 计算数据库student表中数据总数
stat= connection.prepareStatement(sql);
stat.setString(1, stuName);
rs = stat.executeQuery();
while (rs.next()) {
count = rs.getInt(1);
System.out.println(rs.getInt(1));
}
// 执行插入数据操作
stat = connection.prepareStatement(sqlStr);
stat.setString(1, stuName);
stat.setInt(2, gender);
stat.setInt(3, age);
stat.setString(4, address);
stat.setInt(5, count);
stat.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
} finally {
ReleaseResource();
}
}
/**
* 释放资源
*/
public void ReleaseResource() {
if (rs != null) {
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (stat != null) {
try {
stat.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
数据库的连接
最新推荐文章于 2025-04-06 12:13:06 发布