夜观天Xiang

导航

jdbc随笔

通过jdbc连接数据库的基本步骤:
   导入jar包驱动类
   jdbc语法:jdbc:子协议:厂商内容
   对于mysql而言:jdbc:mysql://主机地址:端口号/库名
                                       例:    jdbc:mysql://localhost:3306/test

jdbc获取数据库连接:
 //准备四个参数
 
 //加载数据库驱动类
 
 //利用DriverManager的getConnection方法获取数据库连接

 

代码示例:

//准备四个参数
        String url = "jdbc:mysql://localhost:3306/test";
        String username = "root";
        String password = "123456";
        String driverClass="com.mysql.jdbc.Driver";
        
        Connection conn = null;
        Statement statement=null;
        
        try {
           Class.forName(driverClass);
           //获取数据库连接
           conn = DriverManager.getConnection(url,username,password);
           //statement是具体执行SQL的对象!
           statement = conn.createStatement();
          String sql = "update stu1 set `name` = 'dehua' where id = 1";
          //该executeUpdate方法可以执行sql语句的增删改操作,而且会返回一个结果,这个结果表示受影响的行数!
      }
     catch(Exception e){} finally{ if(statement != null){ try { statement.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } if(conn != null){ try { conn.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }


需要注意:如果是对表的增删改操作我们使用的是:statement.executeUpdate(sql);

posted on 2017-08-13 20:30  夜观天Xiang  阅读(159)  评论(0)    收藏  举报