Home >Database >Mysql Tutorial >java实现MySql连接七步

java实现MySql连接七步

WBOY
WBOYOriginal
2016-06-07 15:34:001155browse

package org.cjit.io.student; /** * java实现MySQl的JDBC连接的七步 */ import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; public class JdbcTest { * @p

 

package org.cjit.io.student;
/**
 * java实现MySQl的JDBC连接的七步
 */

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class JdbcTest {

 

  * @param args
  */
 private static  Connection con;
 public static void main(String[] args) {
  // TODO Auto-generated method stub
  try {
   //1.载入JDBC驱动程序包
   Class.forName("com.mysql.jdbc.Driver");
   //2.定义连接URL
   String url = "jdbc:mysql://localhost:3306/test?user=root&password=root";
   //3.建立连接
   con = DriverManager.getConnection(url);
            //4.创建Statement对象
   Statement stmt = con.createStatement();
   //5.执行查询操作
   String query = "select*from person";
   ResultSet rs = stmt.executeQuery(query);
            //6.对查询结果进行处理
   while (rs.next()) {
    String name=rs.getString("姓名");
    String password=rs.getString("密码");
    System.out.println(rs.getString(2));
    System.out.println(name+":"+password);

   }

  } catch (ClassNotFoundException e) {// 由16行抛出
   // TODO Auto-generated catch block
   e.printStackTrace();
  } catch (SQLException e) {// 由con,stmt抛出
   // TODO Auto-generated catch block
   e.printStackTrace();
  }finally{
   //7.关闭连接
   if(con!=null){
    try {
     con.close();
    } catch (SQLException e) {
     // TODO Auto-generated catch block
      System.exit(0);
    }
    
   }
  }

 }

}

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn