我的環境:MySQL:mysql-essential-5.1.51-win32
安裝之前的準備工作:
jdbc驅動
Eclipse:任意版本,免費的,可以百度的到。
1.MySQL安裝
下面來創建一個數據:
1
2
3
4
|
mysql> CREATE DATABASE test; //創建一個數據庫 mysql>use test; //指定test為當前要操作的數據庫 mysql> CREATE TABLE user ( name VARCHAR (20), password VARCHAR (20)); //創建一個表 user ,設置兩個字段。 mysql> INSERT INTO user VALUES ( 'huzhiheng' , '123456' ); //插入一條數據到表中 |
2.打開Eclipse,創建一個項目(my),
操作:右鍵點擊my--->build Path--->add external Archiver...選擇jdbc驅動,點擊確定。
我的項目列表:
3.驅動已經導入,下面我們來寫一個程序驗證一下
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
|
import java.sql.*; 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" , "198876" ); //連接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(); } } } |
點擊運行程序:
1
2
|
Success loading Mysql Driver! Success connect Mysql server! |
出現上面結果,說明你連接數據庫成功。
4.可以查看到MySQL里面的內容,那我們是不是想往MySQL中插入數據呢。
下面的例子,往MySQL的user表中插入100條數據
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
|
import java.sql.*; public class Myjproject { 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" , "198876" ); int num=100; PreparedStatement Statement= connect .prepareStatement( "INSERT INTO user VALUES(?,?)" ); for ( int i=0;i<num;i++) //定義個100次的循環,往表里插入一百條信息。 { Statement.setString(1, "chongshi" +i); Statement.setString(2, "bo" +i); Statement.executeUpdate(); } // } catch (ClassNotFoundException e) { // TODO Auto-generated catch block // System. out .println( "An error has occurred:" +e.toString()); // e.printStackTrace(); }catch(SQLException e) { } } } |
5.下面我們打開MySQL數據庫進行查看
1
2
3
4
5
|
mysql> show tatabases; //查看所數據庫 mysql> use test; //使test為當前要操作的數據庫 mysql> show tables; //查看當前數據庫的所有表 view sourceprint? mysql> select * from user ; //查看當前表( user )的所有信息 |
注意:如果不能正常連接你的數據庫,請檢查你代碼中,驅動、用戶名、密碼、表等信息是否對應無誤,不要把別人的代碼直接復制過來,看也不看就用。
以上就是用Eclipse連接MySQL數據庫的全部過程,希望對大家的學習有所幫助。