首先要下载Connector/J地址:http://www.mysql.com/downloads/connector/j/
这是MySQL官方提供的连接方式:
解压后得到jar库文件,需要在工程中导入该库文件
我是用的是Eclipse:



JAVA连接MySQL稍微繁琐,所以先写一个类用来打开或关闭数据库:
DBHelper.java
- package com.hu.demo;
-
- import java.sql.Connection;
- import java.sql.DriverManager;
- import java.sql.PreparedStatement;
- import java.sql.SQLException;
-
- public class DBHelper {
- public static final String url = "jdbc:mysql://127.0.0.1/student";
- public static final String name = "com.mysql.jdbc.Driver";
- public static final String user = "root";
- public static final String password = "root";
-
- public Connection conn = null;
- public PreparedStatement pst = null;
-
- public DBHelper(String sql) {
- try {
- Class.forName(name);
- conn = DriverManager.getConnection(url, user, password);
- pst = conn.prepareStatement(sql);
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
-
- public void close() {
- try {
- this.conn.close();
- this.pst.close();
- } catch (SQLException e) {
- e.printStackTrace();
- }
- }
- }
再写一个Demo.java来执行相关查询操作
Demo.java
- package com.hu.demo;
-
- import java.sql.ResultSet;
- import java.sql.SQLException;
-
- public class Demo {
-
- static String sql = null;
- static DBHelper db1 = null;
- static ResultSet ret = null;
-
- public static void main(String[] args) {
- sql = "select *from stuinfo";
- db1 = new DBHelper(sql);
-
- try {
- ret = db1.pst.executeQuery();
- while (ret.next()) {
- String uid = ret.getString(1);
- String ufname = ret.getString(2);
- String ulname = ret.getString(3);
- String udate = ret.getString(4);
- System.out.println(uid + "\t" + ufname + "\t" + ulname + "\t" + udate );
- }
- ret.close();
- db1.close();
- } catch (SQLException e) {
- e.printStackTrace();
- }
- }
-
- }
JAVA使用JDBC连接MySQL数据库
原文:http://www.cnblogs.com/icebutterfly/p/7693892.html