JDBC

时间:2017-08-25 00:41:20   收藏:0   阅读:378

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");

 

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

评论(0
© 2014 bubuko.com 版权所有 - 联系我们:wmxa8@hotmail.com
打开技术之扣,分享程序人生!