java代码中连接数据库需要用JDBC,这篇博客介绍JDBC的最原始的写法:
具体代码如下:
public static void main(String[] args) {
//导入jar包
//加载驱动
Connection conn = null;
Statement stat = null;
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test","root","123456");
String sql ="update student set age = 19 where id =2";
stat = conn.createStatement();
int count= stat.executeUpdate(sql);
if (count>0) {
System.out.println("修改成功");
}else {
System.out.println("修改失败");
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}finally {
try {
if(stat !=null){
stat.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
try {
if(conn !=null){
conn.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
return;
}
private static void Demo1() throws ClassNotFoundException, SQLException {
//导入jar包
//加载驱动
Class.forName("com.mysql.jdbc.Driver");
//获取数据库连接对象
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test","root","123456");
//定义sql语句
String sql2 = "insert into student values(2,11)";
String sql ="update student set age = 18 where id =2";
String sql3 = "delete from student where id=1";
//获取执行sql对象
Statement stat = conn.createStatement();
Statement stat1 =conn.createStatement();
//执行sql语句
int count1 = stat1.executeUpdate(sql);
int count = stat.executeUpdate(sql2);
//处理结果
System.out.print(count);
System.out.println(count1);
//释放资源
stat.close();
stat1.close();
conn.close();
}