JDBC将Java代码与数据库进行连接
时间:2021-07-01 10:21:17
帮助过:3人阅读
java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
public class JDBCDemo {
private static final String URL = "jdbc:mysql://localhost:3306/user
?serverTimezone=UTC"
;//防止出现乱码
private static final String USERNAME = "root"
;
private static final String PWD = "123"
;
public static void update() {
//
Connection connection =
null;
Statement stmt =
null;
try {
// a.导入驱动加载驱动类
Class.forName("com.mysql.cj.jdbc.Driver");
// 加载具体的驱动类
// b.与数据库建立连接
connection =
DriverManager.getConnection(URL, USERNAME, PWD);
// c.发送sql语句执行(增删改查)
stmt =
connection.createStatement();
String sql = "insert into student values(2,‘zs‘,23,‘s1‘)"
;
// String sql = "update student set STUNAME=‘ls‘ where stuno=1";
// String sql = "delete from student where stuno=1";
// 执行sql语句
int count = stmt.executeUpdate(sql);
//
// d.处理结果
if (count > 0
) {
System.out.println("操作成功!"
);
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} catch(Exception e) {
e.printStackTrace();
}
finally {
try {
if(stmt!=
null) stmt.close();
//
if(connection!=
null)connection.close();
}catch(SQLException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
update() ;
}
}
JDBC将Java代码与数据库进行连接
标签:inf nec code ring detail nload dex close exception