1.創建數據庫、表格、具體值
mysql>CREATE DATABASE test;
mysql>use test;
mysql>CREATE TABLE user (name VARCHAR(20),password VARCHAR(20));
mysql>INSERT INTO user VALUES('jacob','050818');
2.打開Eclipse,創建一個項目(my)。
操作:右鍵點擊my—>build Path—>add external Archiver…選擇jdbc驅動,點擊確定。
我的項目列表:
3.具體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");
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" + "");
System.out.println("Success connect Mysql server!");
Statement stmt = connect.createStatement();
ResultSet rs = stmt.executeQuery("select * from 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;
mysql> show tables;
mysql> select *from user;