码迷,mamicode.com
首页 > 数据库 > 详细

JDBC

时间:2017-08-25 01:07:02      阅读:195      评论:0      收藏:0      [点我收藏+]

标签:cio   name   rom   word   set   password   javaee   mail   fun   

JDBC( Java Data Base Connectivity ) is one of the technique of JavaEE.

How to use JDBC to query the data in the table and print the data in the console via java?

  1. Register the sql driver

  2. Get the connection with database

  3. Create the sql statement object

  4. Execute the sql statement

  5. If you execute the query statement, you should handle the result

  6. Close the resource

  for exmaple:

    技术分享

  

public void test() throws Exception{

  // register the driver //DriverManager.register(
new com.mysql.jdbc.Driver()); ----------> not recommended
  Class.forName("com.mysql.jdbc.Driver()");
  // get the connection of database Connection connection
= DriverManager.getConnection("jdbc:mysql://localhost:3306/day15","root","root");
  // create statement object Statement statement
= connection.createStatement();
  // execute the sql statement ResultSet results
= statement.executeQuery(‘SELECT * FROM users‘);
  // get the information in the table
while(results.next()){ String id = results.getObject("id"); String name = results.getObject("name"); String password = results.getObject("password"); String email = results.getObject("email"); String birthday = results.getObject("birthday"); }
  // close the resource results.close(); statement.close(); connection.close(); }

 

DriverManager:

  function:

    1. register the driver:

      Class.forName("com.mysql.jdbc.Driver");

    2. get the connection:

      Connection connection = DriverManager.getConnecion("jdbc:mysql://localhost:3306/mydb1","root","root");

          技术分享

      three ways to get the connection:

        method1:

          DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb1","root","root");

        method2:

          Properties prop = new Properties();

          prop.put("user","root");

          prop.put("password","root");

          DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb1",prop);

        method3:

          DriverManager.getConnection("jdbc:mysql://localhost:3306?user=root&password=root");

 

JDBC

标签:cio   name   rom   word   set   password   javaee   mail   fun   

原文地址:http://www.cnblogs.com/ppcoder/p/7425832.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!