public class Demo05 {
public static void main(String[] args) throws ClassNotFoundException {
//注册驱动,告诉程序使用哪个数据库驱动jar
Class.forName("com.mysql.jdbc.Driver");
//定义连接数据库变量
Connection connection = null;
//定义执行sql语句的变量
Statement statement = null;
try {
//通过驱动管理的静态方法获取连接数据库的对象
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/db2", "root", "150134");
//通过连接数据库对象获取执行sql语句的对象
statement = connection.createStatement();
//定义一个sql语句,在数据库中插入一条数据
String sql = "insert into java_score values('郭靖', '一班', 90)";
//这里的count是sql语句执行成功的条数
int count = statement.executeUpdate(sql);
//上面的sql语句执行成功的话这里会打印出1
System.out.println(count);
} catch (SQLException e) {
e.printStackTrace();
}finally {
//关闭资源,先对其进行非空判断,下面同理
if (statement != null) {
try {
statement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (connection != null) {
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
}
使用jdbc链接数据库(每行代码有解释)
最新推荐文章于 2022-12-12 08:00:00 发布