jdbc 連接 mysql
一、安裝
ubuntu(linux)下安裝mysql
$ sudo apt-get update
$ sudo apt-get install mysql-server mysql-client
安裝完成後會讓你設置一下root用戶的密碼,這裏的root用戶是mysql的root用戶,和系統的root用戶不同。
登錄mysql
mysql -uroot -p
二、設置遠程連接
主要設置兩個點,1. mysql的監聽端口(3306)是不是阻止的,主要看防火牆。
ubuntu防火牆設置 可以參考 http://blog.csdn.net/u012480384/article/details/50822304
windows條件下,自行百度一下,應該有很多。
2. mysql內部設置遠程連接,並授權。
vim /etc/my.cnf
註釋這一行:bind-address=127.0.0.1 ==> #bind-address=127.0.0.1
保存退出。
對應的window版本的 mysql 目錄下 my.cnf 文件
設置mysql:
#登錄mysqlmysql -uroot -p
#切換到 'mysql'數據庫,修改遠程連接的基本信息,保存在mysql數據庫中,因此使用mysql數據庫。
mysql> use mysql;
# *.* 用來設置 數據庫和表名
# To 'root'@'%' 用來設置得到授權的用戶和所在的ip。
# By 'root' 表示得到授權用戶的登錄密碼
mysql> GRANT ALL PRIVILEGES ON *.* TO 'root'@'%' IDENTIFIED BY 'root' WITH GRANT OPTION;
# 刷新授權,使之生效
mysql> flush privileges;
# 檢驗
mysql> select host,user from user;
三、 java 代碼
首選需要引入mysql jdbc的jar包Java連接MySQL的最新驅動包下載地址
http://www.mysql.com/downloads/connector/j
java代碼
package com.test.mysql;
import com.mysql.jdbc.Connection;
import com.mysql.jdbc.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.List;
//MySQL的JDBC URL編寫方式:jdbc:mysql://主機名稱:連接端口/數據庫的名稱?參數=值
// 避免中文亂碼要指定useUnicode和characterEncoding
// 執行數據庫操作之前要在數據庫管理系統上創建一個數據庫,名字自己定,
// 下面語句之前就要先創建javademo數據庫
public class MysqlHelper {
// public static final String url = "jdbc:mysql://127.0.0.1:3306/student";
public static final String MYSQL_JDBC = "jdbc:mysql://192.168.1.164:3306/student";
public static final String MYSQL_DRIVER = "com.mysql.jdbc.Driver";
public static final String MYSQL_USER = "root";
public static final String MYSQL_PASSWORD = "root";
public static final String MYSQL_URL = MYSQL_JDBC + "?user=root&password=root&useUnicode=true&characterEncoding=UTF8";
public static final String TABLE_NAME = "student";
public static final String TABLE_COLUMN = TABLE_NAME + "(name)";
private Connection conn = null;
// private PreparedStatement pst = null;
public MysqlHelper() {
try {
Class.forName(MYSQL_DRIVER);// 指定連接類型
System.out.println("成功加載MySQL驅動程序");
conn = (Connection) DriverManager.getConnection(MYSQL_URL);// 獲取連接
conn.setCharacterEncoding("utf8");
conn.setUseCompression(true);
if (conn.getUseCompression()) {
System.out.println("compress");
} else {
System.out.println("UnCompress");
}
// pst = conn.prepareStatement(sql);// 準備執行語句
} catch (Exception e) {
e.printStackTrace();
}
}
private void execute(String sql) {
if (null == sql || 0 == sql.length()) {
System.out.println("argu wrong");
return;
}
System.out.println(sql);
Statement stmt;
try {
stmt = conn.createStatement();
int result = stmt.executeUpdate(sql);
if (-1 == result) {
System.out.println("execute failure " + result);
} else {
System.out.println("execute successed " + result);
}
} catch (SQLException e) {
e.printStackTrace();
}
}
private void executeQuery(String sql) {
if (null == sql || 0 == sql.length()) {
System.out.println("argu wrong");
return;
}
ResultSet rs = null;
System.out.println(sql);
Statement stmt;
try {
stmt = conn.createStatement();
rs = stmt.executeQuery(sql);
System.out.println("\n############");
while (rs.next()) {
System.out.println(rs.getInt("id") + " " + rs.getString("name"));
}
System.out.println("############\n");
} catch (SQLException e) {
e.printStackTrace();
}
}
public void insert(String name) {
if (null == name || 0 == name.length())
name = "default";
String sql = "insert into " + TABLE_COLUMN + " values('" + name + "')";
execute(sql);
}
public void insert(List<String> list) {
if (null == list || 0 == list.size())
return;
StringBuilder names = new StringBuilder();
int i = 0;
for (i = 0; i < list.size() - 1; ++i) {
names.append("('" + list.get(i) + "'), ");
}
names.append("('" + list.get(i) + "')");
String sql = "insert into " + TABLE_COLUMN + " values" + names.toString();
execute(sql);
}
public void delete(int id) {
String sql = "delete from " + TABLE_NAME + " where id = " + id;
execute(sql);
}
public void delete(String name) {
if (null == name || 0 == name.length())
name = "default";
String sql = "delete from " + TABLE_NAME + " where name = '" + name + "'";
execute(sql);
}
public void deleteAll() {
String sql = "delete from " + TABLE_NAME;
execute(sql);
}
public void update(int id, String name) {
if (null == name || 0 == name.length())
name = "default";
String sql = "update student set name='" + name + "' where id = " + id;
execute(sql);
}
public void select(int id) {
String sql = "select * from " + TABLE_NAME + " where id = " + id;
executeQuery(sql);
}
public void selectAll() {
String sql = "select * from " + TABLE_NAME;
executeQuery(sql);
}
public void createTable() {
createTable(TABLE_NAME);
}
public void createTable(String tableName) {
if (null == tableName || 0 == tableName.length())
tableName = TABLE_NAME;
if (!hasTable(tableName)) {
String sql = "create table " + tableName
+ " (id int(4) not null primary key auto_increment,name varchar(20) not null)engine=innodb default charset=utf8";
execute(sql);
}
}
public boolean hasTable(String tableName) {
if (null == tableName || 0 == tableName.length())
tableName = TABLE_NAME;
DatabaseMetaData meta = null;
ResultSet result = null;
try {
meta = (DatabaseMetaData) conn.getMetaData();
result = meta.getTables(null, null, tableName, null);
if (result.next())
return true;
return false;
} catch (SQLException e) {
e.printStackTrace();
}
return false;
}
public void dropTable(String tableName) {
if (null == tableName || 0 == tableName.length())
tableName = TABLE_NAME;
if (hasTable(tableName)) {
String sql = "drop table " + tableName;
execute(sql);
}
}
public void dropTable() {
dropTable(TABLE_NAME);
}
public void commit() {
String sql = "commit";
execute(sql);
}
public void close() {
try {
this.conn.close();
// this.pst.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
測試代碼:
package com.test.mysql;
import java.util.Arrays;
public class MysqlDemo {
public static String[] names = {"apple", "bob", "carry", "david"};
public static void main(String[] args) throws Exception {
// connect();
// create();
// drop();
// insert();
// update();
// delete();
// select();
allTest();
System.out.println("###########");
}
public static void connect() {
MysqlHelper mysql = new MysqlHelper();
mysql.close();
}
public static void create() {
MysqlHelper mysql = new MysqlHelper();
mysql.createTable();
mysql.close();
}
public static void drop() {
MysqlHelper mysql = new MysqlHelper();
mysql.dropTable();
mysql.close();
}
public static void insert() {
MysqlHelper mysql = new MysqlHelper();
mysql.insert(Arrays.asList(names));
mysql.close();
}
public static void update() {
MysqlHelper mysql = new MysqlHelper();
mysql.update(1, "xoxo");
mysql.close();
}
public static void delete() {
MysqlHelper mysql = new MysqlHelper();
mysql.delete("apple");
mysql.close();
}
public static void select() {
MysqlHelper mysql = new MysqlHelper();
mysql.selectAll();
mysql.close();
}
public static void allTest() {
MysqlHelper mysql = new MysqlHelper();
if (mysql.hasTable(MysqlHelper.TABLE_NAME)) {
mysql.dropTable();
}
mysql.createTable();
mysql.insert(Arrays.asList(names));
mysql.selectAll();
mysql.update(1, "xoxo");
mysql.selectAll();
mysql.delete(1);
mysql.selectAll();
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
mysql.commit();
mysql.dropTable();
mysql.close();
}
}