search
尋找貓咪~QQ 地點 桃園市桃園區 Taoyuan , Taoyuan

java連接Mysql資料庫

我們連接在使用Java連接資料庫的時候,不管是Oracle資料庫還是Mysql資料庫,都需要一個對應的jar包,Oracle資料庫需要的是ojdbc15.jar包,而Mysql資料庫需要的是mysql-connector-java-5.1.7-bin.jar包,這兩種在網上都可以很方便的找到。2、Java連接Mysql的代碼如下:

private static String url = "jdbc:mysql://localhost:3306/test";

private static String userName = "root";

private static String password = "root";

public static void main(String args) {

MysqlConnectTest mysql= new MysqlConnectTest;

Connection con = mysql.getConnection;

if(con==null){

System.out.println("與mysql資料庫連接失敗!");

}else{

System.out.println("與mysql資料庫連接成功!");

}

}

3、MysqlConnectTest 類中getConnection方法如下:

public Connection getConnection{

Connection con = null;

try {

Class.forName("com.mysql.jdbc.Driver");

con = DriverManager.getConnection(url, userName, password);

} catch (ClassNotFoundException e) {

e.printStackTrace;

} catch (SQLException e) {

e.printStackTrace;

}

return con;

}

4、Mysql執行查看語句:

Statement sts = null;

String sql = "select * from user_table ";

ResultSet resul = null;

try {

sts = (Statement) con.createStatement;

resul = sts.executeQuery(sql);

} catch (SQLException e) {

e.printStackTrace;

}

System.out.println("查詢的結果如下:");

while(resul.next){

System.out.println("user_id: "+resul.getString("user_id")+",user_name: "+resul.getString("user_name")+",user_sex: "+resul.getString("user_sex"));

}

5、現在執行插入語句,代碼如下:

String sql = "insert into user_table values ('3','thiscode','1','28','13351210773')";

int i = 0;

try {

sts = (Statement) con.createStatement;

i = sts.executeUpdate(sql);

if(i == -1){

System.out.println("插入失敗");

}else{

System.out.println("插入成功");

}

} catch (SQLException e) {

e.printStackTrace;

}

步驟閱讀END



熱門推薦

本文由 yidianzixun 提供 原文連結

寵物協尋 相信 終究能找到回家的路
寫了7763篇文章,獲得2次喜歡
留言回覆
回覆
精彩推薦