Eclipse連接MySQL數(shù)據(jù)庫(kù)(傻瓜篇)
我的環(huán)境:MySQL:mysql-essential-5.1.51-win32
jdbc驅(qū)動(dòng):我已經(jīng)上傳到csdn上一個(gè):http://download.csdn.net/source/3451945
Eclipse:任意版本,免費(fèi)的,可以百度的到。
1。MySQL安裝,不會(huì)的朋友可以看連接:http://www.duote.com/tech/1/2430_1.html
下面來創(chuàng)建一個(gè)數(shù)據(jù):
mysql>CREATE DATABASE test; //創(chuàng)建一個(gè)數(shù)據(jù)庫(kù)
mysql>use test; //指定test為當(dāng)前要操作的數(shù)據(jù)庫(kù)
mysql>CREATE TABLE user (name VARCHAR(20),password VARCHAR(20)); //創(chuàng)建一個(gè)表user,設(shè)置兩個(gè)字段。
mysql>INSERT INTO user VALUES('huzhiheng','123456'); //插入一條數(shù)據(jù)到表中
2。打開Eclipse,創(chuàng)建一個(gè)項(xiàng)目(my),
操作:右鍵點(diǎn)擊my--->build Path--->add external Archiver...選擇jdbc驅(qū)動(dòng),點(diǎn)擊確定。
我的項(xiàng)目列表:
3。驅(qū)動(dòng)已經(jīng)導(dǎo)入,下面我們來寫一個(gè)程序驗(yàn)證一下
import java.sql.*;
public class MysqlJdbc {
public static void main(String args[]) {
try {
Class.forName("com.mysql.jdbc.Driver"); //加載MYSQL JDBC驅(qū)動(dòng)程序
//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//服務(wù)器地址/數(shù)據(jù)庫(kù)名 ,后面的2個(gè)參數(shù)分別是登陸用戶名和密碼
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();
}
}
}
點(diǎn)擊運(yùn)行程序:
Success loading Mysql Driver!
Success connect Mysql server!
huzhiheng
出現(xiàn)上面結(jié)果,說明你連接數(shù)據(jù)庫(kù)成功。
import java.sql.*;
public class Myjproject {
public static void main(String args[])
{
try {
Class.forName("com.mysql.jdbc.Driver"); //加載MYSQL JDBC驅(qū)動(dòng)程序
//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++) //定義個(gè)100次的循環(huán),往表里插入一百條信息。
{
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數(shù)據(jù)庫(kù)進(jìn)行查看
注意:如果不能正常連接你的數(shù)據(jù)庫(kù),請(qǐng)檢查你代碼中,驅(qū)動(dòng)、用戶名、密碼、表等信息是否對(duì)應(yīng)無誤,不要把別人的代碼直接復(fù)制過來,看也不看就用。
posted on 2012-05-02 14:48 順其自然EVO 閱讀(529) 評(píng)論(0) 編輯 收藏