1、下载My SQL Jar包 下载地址:http://www.mysql.com/downloads/connector/j/
2、导入Jar包
3、新建一个DB帮助类
DBHelper.java
package com.chenjun.test1;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
/**
* 作者: 陈骏
* 时间:2017/9/13 0013
* QQ:200622550
* 作用:数据库连接操作
*/
public class DBHelper {
public static final String url = "jdbc:mysql://127.0.0.1/test_db";
public static final String name = "com.mysql.jdbc.Driver";
public static final String user = "root";
public static final String password = "652300";
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();
}
}
}
4、数据库操作(引用方法)
/**
* 查询数据
*/
private static void queue() {
String sql = "select * from cj_db";
ResultSet rs = null;
DBHelper dbHelper = null;
dbHelper = new DBHelper(sql);
try {
rs = dbHelper.pst.executeQuery();
while (rs.next()) {
System.out.println(rs.getInt("id") + "\t" + rs.getString("name") + "\t" + rs.getInt("age"));
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
rs.close();
dbHelper.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
/**
* 添加数据
*/
private static void add() {
String sql = "INSERT INTO cj_db (name, age) VALUES ('小明',19)";
DBHelper dbHelper = null;
dbHelper = new DBHelper(sql);
try {
int a = dbHelper.pst.executeUpdate();
System.out.println("数据更新了 " + a + " 条数据");
} catch (Exception e) {
e.printStackTrace();
} finally {
dbHelper.close();
}
}