转载地址:http://hzy3774.iteye.com/blog/1689525
首先要下载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();
- }
- }
- }