importjava.sql.Connection;importjava.sql.DriverManager;importjava.sql.ResultSet;importjava.sql.Statement;publicclassMysqlJdbc{publicstaticvoidmain(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條數據
importjava.sql.Connection;importjava.sql.DriverManager;importjava.sql.PreparedStatement;importjava.sql.SQLException;publicclassMyproject{publicstaticvoidmain(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;PreparedStatementStatement=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)的所有信息
1.創建數據庫、表格、具體值
2.打開Eclipse,創建一個項目(my)。
操作:右鍵點擊my—>build Path—>add external Archiver…選擇jdbc驅動,點擊確定。
我的項目列表:
3.具體Java代碼如下:(注意:代碼不能直接用,需要你的用戶名和密碼)
點擊運行程序:
出現上面結果,說明你連接數據庫成功。
下面的例子,往MySQL的user表中插入100條數據
下面我們打開MySQL數據庫進行查看
回答所涉及的環境:聯想天逸510S、Windows 10。