1. 程式人生 > >Eclipse連線MySQL資料庫(詳細步驟)

Eclipse連線MySQL資料庫(詳細步驟)

本人在寫這篇部落格的時候也是菜鳥一隻,百度“Java連線mysql資料庫、eclipse連線資料庫”等文章一大堆,可總是報錯。

下面的操作是經本人驗證,確實可行,包括了jar包匯入、用jdbc連線mysql之前,新建資料庫,新建表格,插入資料的操作。

首先

建立資料庫、表格、具體值

mysql>CREATE   DATABASE test;   //建立一個數據庫

mysql>use  test;  //指定test為當前要操作的資料庫

mysql>CREATE  TABLE  user (name VARCHAR(20),password VARCHAR(20));   //建立一個表user,設定兩個欄位。

mysql>INSERT  INTO  user  VALUES('jacob','050818'); //插入一條資料到表中

第二步

開啟Eclipse,建立一個專案(TestMySQL),

操作:右鍵點選TestMySQL--->build Path--->add external Archiver...選擇jdbc驅動,點選確定。


我的專案列表:


第三步

具體Java程式碼如下:(注意:程式碼不能直接用,需要需要你的使用者名稱和密碼)

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class MysqlJdbc {
public static void main(String args[]) {
	try {
		Class.forName("com.mysql.jdbc.Driver");     //載入MYSQL JDBC驅動程式   
		//Class.forName("org.gjt.mm.mysql.Driver");
		System.out.println("Success loading Mysql Driver!");
		} catch (Exception e) {
			System.out.print("Error loading Mysql Driver!");
			e.printStackTrace();
		}
		try {
			Connection connect = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root",
					"050818" + "");
			// 連線URL為 jdbc:mysql//伺服器地址/資料庫名 ,後面的2個引數分別是登陸使用者名稱和密碼

			System.out.println("Success connect Mysql server!");
			Statement stmt = connect.createStatement();
			ResultSet rs = stmt.executeQuery("select * from user");
			// user 為你表的名稱
			while (rs.next()) {
				System.out.println(rs.getString("name"));
			}
    }catch (Exception e) {
    	System.out.print("get data error!");
    	e.printStackTrace();
    }
  }
}

點選執行程式:  

Success loading Mysql Driver!

Success connect Mysql server!

jacob  

出現上面結果,說明你連線資料庫成功。

下面的例子,往MySQL的user表中插入100條資料
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;




public class Myproject {


public static void main(String[] args) {
try{
Class.forName("com.mysql.jdbc.Driver");
System.out.println("Success loading MySQL Drive");
}catch(Exception e){
System.out.println("Error loading MySQL Driver!");
e.printStackTrace();
}
try{
Connection connect=DriverManager.getConnection(
"jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8&useSSL=false","root","050818");
int num=100;
PreparedStatement Statement=connect.prepareStatement("INSERT INTO user VALUES(?,?)");
for(int i=0;i<num;i++){
Statement.setString(1,"chongshi"+i);
Statement.setString(2,"bo"+i);
Statement.executeUpdate();
}


   }catch(SQLException e){}
}
}


下面我們開啟MySQL資料庫進行檢視 

 
mysql> show databases;  //檢視所資料庫
mysql> use  test;    //使test為當前要操作的資料庫
mysql> show tables; //檢視當前資料庫的所有表
mysql> select *from user;  //檢視當前表(user)的所有資訊