jdbc连接数据库

1.DriverManger类
          管理和作用驱动    在Mysql5之后可以省略不写
               创建数据库连接   DriverManger.getConnection(String url,String url,String password)
           使用JDBC连接数据库四个参数介绍
                 用户名:登录的用户名
                 密码 : 登陆的密码
                 连接url  mysql的写法:jdbc:mysql://localhost:3306/数据库名
                 协议:                       子协议   ://服务器或者IP地址:端口号?参数=参数名
jdbc:mysql://localhost:3306/数据库名   可以简写:jdbc:mysql///数据库名

Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql:///user", "root", "root");

2.使用Connection接口
        作用  获取数据库连接
         功能
              获取执行的sql对象
管理事务:
      开启事务: setAutoCommit();
      提交验证: commit;
      回滚事务: rollback();
Statement createStatement();
        PreParedSatement PrePareStatement(String sql); 

3.能够使用Statement接口
       作用 :执行Sql对象
        方法:
  
     Boolean execute(String sql) ;*了解 可以执行任意sql语句
int executeUpdate(String sql); 执行 DML(insert update delete)
                               DDL(create alter drop) 
ResuletSet  executeQuery(String sql);  DQL(select)

4.能够使用PreparedStatement完成增删改查

     Statement createStatement();
  改为     PreParedSatement PrePareStatement(String sql); 

例如:public static void main(String[] args) {
        try {
            Class.forName("com.mysql.jdbc.Driver");
            connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/qy97", "root", "root");
            String sql="insert into users values(null,'李登','sfsdfdsf')";
            statement = connection.createStatement();
            int i = statement.executeUpdate(sql);
            System.out.println(i);
            if (i>0){
                System.out.println("添加成功");
            }else{
                System.out.println("添加失败");
            }

        } catch (Exception 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();
                }
            }
        }
    }
原文地址:https://www.cnblogs.com/qurui1998/p/10639754.html