JAVA使用JDBC连接MySQL数据库

首先要下载Connector/J地址:http://www.mysql.com/downloads/connector/j/

这是MySQL官方提供的连接方式:

解压后得到jar库文件,需要在工程中导入该库文件

我是用的是Eclipse:



 

 

 JAVA连接MySQL稍微繁琐,所以先写一个类用来打开或关闭数据库:

DBHelper.java

Java代码  
  1. package com.hu.demo;  
  2.   
  3. import java.sql.Connection;  
  4. import java.sql.DriverManager;  
  5. import java.sql.PreparedStatement;  
  6. import java.sql.SQLException;  
  7.   
  8. public class DBHelper {  
  9.     public static final String url = "jdbc:mysql://127.0.0.1/student";  
  10.     public static final String name = "com.mysql.jdbc.Driver";  
  11.     public static final String user = "root";  
  12.     public static final String password = "root";  
  13.   
  14.     public Connection conn = null;  
  15.     public PreparedStatement pst = null;  
  16.   
  17.     public DBHelper(String sql) {  
  18.         try {  
  19.             Class.forName(name);//指定连接类型  
  20.             conn = DriverManager.getConnection(url, user, password);//获取连接  
  21.             pst = conn.prepareStatement(sql);//准备执行语句  
  22.         } catch (Exception e) {  
  23.             e.printStackTrace();  
  24.         }  
  25.     }  
  26.   
  27.     public void close() {  
  28.         try {  
  29.             this.conn.close();  
  30.             this.pst.close();  
  31.         } catch (SQLException e) {  
  32.             e.printStackTrace();  
  33.         }  
  34.     }  
  35. }  

再写一个Demo.java来执行相关查询操作

Demo.java

Java代码  收藏代码
    1. package com.hu.demo;  
    2.   
    3. import java.sql.ResultSet;  
    4. import java.sql.SQLException;  
    5.   
    6. public class Demo {  
    7.   
    8.     static String sql = null;  
    9.     static DBHelper db1 = null;  
    10.     static ResultSet ret = null;  
    11.   
    12.     public static void main(String[] args) {  
    13.         sql = "select *from stuinfo";//SQL语句  
    14.         db1 = new DBHelper(sql);//创建DBHelper对象  
    15.   
    16.         try {  
    17.             ret = db1.pst.executeQuery();//执行语句,得到结果集  
    18.             while (ret.next()) {  
    19.                 String uid = ret.getString(1);  
    20.                 String ufname = ret.getString(2);  
    21.                 String ulname = ret.getString(3);  
    22.                 String udate = ret.getString(4);  
    23.                 System.out.println(uid + " " + ufname + " " + ulname + " " + udate );  
    24.             }//显示数据  
    25.             ret.close();  
    26.             db1.close();//关闭连接  
    27.         } catch (SQLException e) {  
    28.             e.printStackTrace();  
    29.         }  
    30.     }  
    31.   
    32. }  
原文地址:https://www.cnblogs.com/icebutterfly/p/7693892.html