//方法
1、利用构造函数或单例初始化函数,实现数据库的连接
2、提供通用查询函数(接受SELECT操作)
3、提供通用的插入函数(接受INSERT操作)
4、提供通用的修改函数(接受UPDATE操作)
5、提供通用的删除函数(接受DELETE操作)
6、利用析构函数或单例销毁函数,实现数据库的关闭(JAVA使用 finalize)
public class JDBCDemo {
public static void update(){
//增删改Connection connection = null;Statement stmt = null;try {
//导入驱动,加载具体的驱动类 Class.forName("com.mysql.cj.jdbc.Driver");//加载具体的驱动类//与数据库建立连接connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/数据库名?serverTimezone=GMT%2B8","用户名","密码");//创建表名称为student,分别创建字段:stuno,stuname,stuage,gname//发送sql,执行(增删改)stmt = connection.createStatement();String sql = "insert into student values(2,'ls',20,'rg8')";
// String sql = "update student set STUAGE=21 where stuno=1";
// String sql = "delete from student where stuno=1";//执行sql(增删改executeUpdate)int count = stmt.executeUpdate(sql);//返回值表示增删改几条数据//处理结果if(count>0) {
System.out.print("操作成功!");}}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 query() {
Connection connection = null;Statement stmt = null;ResultSet rs = null;try {
//导入驱动,加载具体的驱动类 Class.forName("com.mysql.cj.jdbc.Driver");//加载具体的驱动类//与数据库建立连接
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/数据库名?serverTimezone=GMT%2B8","用户名","密码");//发送sql,执行(查)stmt = connection.createStatement();
// String sql = "select stuno,stuname from student";
// String sql = "select * from student";String sql = "select * from student where stuname like '%l%'";//执行sql(查询executeQuery)rs = stmt.executeQuery(sql);//返回值表示增删改几条数据//处理结果while(rs.next()) {
int sno =rs.getInt("stuno");String sname =rs.getString("stuname");
// int sno =rs.getInt(1);//下标:从1开始计数
// String sname =rs.getString(2);System.out.println(sno+"--"+sname);}}catch(ClassNotFoundException e){
e.printStackTrace();}catch(SQLException e){
e.printStackTrace();}catch(Exception e){
e.printStackTrace();}finally {
try {
if(rs!=null)rs.close();if(stmt!=null)stmt.close();//对象.方法if(connection!=null)connection.close();}catch(SQLException e){
e.printStackTrace();}}}public static void main(String[] args) {
// update();query();}
}