首先你要導(dǎo)包

專注于為中小企業(yè)提供成都網(wǎng)站建設(shè)、成都網(wǎng)站設(shè)計(jì)服務(wù),電腦端+手機(jī)端+微信端的三站合一,更高效的管理,為中小企業(yè)婺城免費(fèi)做網(wǎng)站提供優(yōu)質(zhì)的服務(wù)。我們立足成都,凝聚了一批互聯(lián)網(wǎng)行業(yè)人才,有力地推動(dòng)了上千企業(yè)的穩(wěn)健成長(zhǎng),幫助中小企業(yè)通過(guò)網(wǎng)站建設(shè)實(shí)現(xiàn)規(guī)模擴(kuò)充和轉(zhuǎn)變。
JDBC連接數(shù)據(jù)庫(kù) ?
?創(chuàng)建一個(gè)以JDBC連接數(shù)據(jù)庫(kù)的程序,包含7個(gè)步驟:
1、加載JDBC驅(qū)動(dòng)程序:
在連接數(shù)據(jù)庫(kù)之前,首先要加載想要連接的數(shù)據(jù)庫(kù)的驅(qū)動(dòng)到JVM(Java虛擬機(jī)),
這通過(guò)java.lang.Class類的靜態(tài)方法forName(String ?className)實(shí)現(xiàn)。
例如:
try{
//加載MySql的驅(qū)動(dòng)類
Class.forName("com.mysql.jdbc.Driver") ;
}catch(ClassNotFoundException e){
System.out.println("找不到驅(qū)動(dòng)程序類 ,加載驅(qū)動(dòng)失敗!");
e.printStackTrace() ;
}
成功加載后,會(huì)將Driver類的實(shí)例注冊(cè)到DriverManager類中。
2、提供JDBC連接的URL
?連接URL定義了連接數(shù)據(jù)庫(kù)時(shí)的協(xié)議、子協(xié)議、數(shù)據(jù)源標(biāo)識(shí)。 ? ? ?
?書(shū)寫形式:協(xié)議:子協(xié)議:數(shù)據(jù)源標(biāo)識(shí)
協(xié)議:在JDBC中總是以jdbc開(kāi)始 ? ? ? 子協(xié)議:是橋連接的驅(qū)動(dòng)程序或是數(shù)據(jù)庫(kù)管理系統(tǒng)名稱。
數(shù)據(jù)源標(biāo)識(shí):標(biāo)記找到數(shù)據(jù)庫(kù)來(lái)源的地址與連接端口。
例如:
(MySql的連接URL)
jdbc:mysql: ? ? ? ? ? //localhost:3306/test?useUnicode=truecharacterEncoding=gbk ;
useUnicode=true:
表示使用Unicode字符集。如果characterEncoding設(shè)置為 ? ? ?gb2312或GBK,本參數(shù)必須設(shè)置為true 。characterEncoding=gbk:字符編碼方式。
3、創(chuàng)建數(shù)據(jù)庫(kù)的連接
?要連接數(shù)據(jù)庫(kù),需要向java.sql.DriverManager請(qǐng)求并獲得Connection對(duì)象, ? ? ? ?該對(duì)象就代表一個(gè)數(shù)據(jù)庫(kù)的連接。
?使用DriverManager的getConnectin(String url , String username , ? ? ? ?String password )方法傳入指定的欲連接的數(shù)據(jù)庫(kù)的路徑、數(shù)據(jù)庫(kù)的用戶名和 ? ? ? ?密碼來(lái)獲得。
例如: ? ? ? ?//連接MySql數(shù)據(jù)庫(kù),用戶名和密碼都是root
String url = "jdbc:mysql://localhost:3306/test" ;
String username = "root" ;
String password = "root" ;
try{ ? ? ?
Connection con = ? ? ? ? ? ? ? ? DriverManager.getConnection(url , username , password ) ;
}catch(SQLException se){
System.out.println("數(shù)據(jù)庫(kù)連接失敗!");
se.printStackTrace() ;
}
4、創(chuàng)建一個(gè)Statement
?要執(zhí)行SQL語(yǔ)句,必須獲得java.sql.Statement實(shí)例,Statement實(shí)例分為以下3 ? ? ? 種類型:
1、執(zhí)行靜態(tài)SQL語(yǔ)句。通常通過(guò)Statement實(shí)例實(shí)現(xiàn)。
2、執(zhí)行動(dòng)態(tài)SQL語(yǔ)句。通常通過(guò)PreparedStatement實(shí)例實(shí)現(xiàn)。 ? ? ? ?
3、執(zhí)行數(shù)據(jù)庫(kù)存儲(chǔ)過(guò)程。通常通過(guò)CallableStatement實(shí)例實(shí)現(xiàn)。
具體的實(shí)現(xiàn)方式:
Statement stmt = con.createStatement() ; ? ? ? ? ?PreparedStatement pstmt = con.prepareStatement(sql) ; ? ? ? ? ?CallableStatement cstmt = ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?con.prepareCall("{CALL demoSp(? , ?)}") ; ? ?
5、執(zhí)行SQL語(yǔ)句
Statement接口提供了三種執(zhí)行SQL語(yǔ)句的方法:executeQuery 、executeUpdate ? ? ?和execute
1、ResultSet executeQuery(String sqlString):執(zhí)行查詢數(shù)據(jù)庫(kù)的SQL語(yǔ)句 ? ? ? ? ? ,返回一個(gè)結(jié)果集(ResultSet)對(duì)象。
2、int executeUpdate(String sqlString):用于執(zhí)行INSERT、UPDATE或 ? ? ? ? ? DELETE語(yǔ)句以及SQL DDL語(yǔ)句,如:CREATE TABLE和DROP TABLE等 ? ? ? ?
3、execute(sqlString):用于執(zhí)行返回多個(gè)結(jié)果集、多個(gè)更新計(jì)數(shù)或二者組合的 ? ? ? ? ? 語(yǔ)句。 ? ? ?具體實(shí)現(xiàn)的代碼:
ResultSet rs = stmt.executeQuery("SELECT * FROM ...") ; ? ? ? int rows = stmt.executeUpdate("INSERT INTO ...") ; ? ? ? boolean flag = stmt.execute(String sql) ; ? ?
6、處理結(jié)果 ? ? ? 兩種情況:
1、執(zhí)行更新返回的是本次操作影響到的記錄數(shù)。
2、執(zhí)行查詢返回的結(jié)果是一個(gè)ResultSet對(duì)象。
? ResultSet包含符合SQL語(yǔ)句中條件的所有行,并且它通過(guò)一套get方法提供了對(duì)這些 ? ? ? ? 行中數(shù)據(jù)的訪問(wèn)。
? 使用結(jié)果集(ResultSet)對(duì)象的訪問(wèn)方法獲取數(shù)據(jù):
while(rs.next()){
String name = rs.getString("name") ;
String pass = rs.getString(1) ; // 此方法比較高效
} ? ? ?
(列是從左到右編號(hào)的,并且從列1開(kāi)始)
7、關(guān)閉JDBC對(duì)象
操作完成以后要把所有使用的JDBC對(duì)象全都關(guān)閉,以釋放JDBC資源,關(guān)閉順序和聲 ? ? ? ?明順序相反:
1、關(guān)閉記錄集
2、關(guān)閉聲明
3、關(guān)閉連接對(duì)象
if(rs != null){ ? // 關(guān)閉記錄集
try{
rs.close() ;
}catch(SQLException e){
e.printStackTrace() ;
}
}
if(stmt != null){ ? // 關(guān)閉聲明
try{
stmt.close() ;
}catch(SQLException e){
e.printStackTrace() ;
}
}
if(conn != null){ ?// 關(guān)閉連接對(duì)象
try{
conn.close() ;
}catch(SQLException e){
e.printStackTrace() ;
}
}
根據(jù)下面這幾個(gè)步驟,選擇操作
①
首先把mysql的服務(wù)停掉
在運(yùn)行窗口輸入:net
stop
mysql
②
把服務(wù)器和客戶端的字符集改成自己想用的字符集:gb2312或是utf8等……
具體操作為:打開(kāi)mysql安裝目錄下的myini.tet;
找到default-character-set,將其改為自己想用的字符集:gb2312或是utf8等……,要注意的是這里有兩個(gè)default-character-set,用ctrl+f定位在文件最前面輸入default就會(huì)找到,都要改過(guò)來(lái);
③
重啟mysql服務(wù)器,在運(yùn)行窗口輸入:net
start
mysql
④
最重要的是一點(diǎn)是,到這里我們已經(jīng)能夠解決亂碼問(wèn)題了,可問(wèn)題是我們依然還會(huì)出現(xiàn)亂碼問(wèn)題,這是因?yàn)槲覀儸F(xiàn)在的表被創(chuàng)建的時(shí)候用的是默認(rèn)的字符集(latin1),所以這時(shí)候我們要把表刪除,然后重建就可以了
import java.sql.*;
public class DataBasePractice {
public static void main(String[] args) {
//聲明Connection對(duì)象
Connection con;
//驅(qū)動(dòng)程序名
String driver = "com.mysql.jdbc.Driver";
//URL指向要訪問(wèn)的數(shù)據(jù)庫(kù)名mydata
String url = "jdbc:mysql://localhost:3306/mydata";
//MySQL配置時(shí)的用戶名
String user = "root";
//MySQL配置時(shí)的密碼
String password = "root";
//遍歷查詢結(jié)果集
try {
//加載驅(qū)動(dòng)程序
Class.forName(driver);
//1.getConnection()方法,連接MySQL數(shù)據(jù)庫(kù)!!
con = DriverManager.getConnection(url,user,password);
if(!con.isClosed())
System.out.println("Succeeded connecting to the Database!");
//2.創(chuàng)建statement類對(duì)象,用來(lái)執(zhí)行SQL語(yǔ)句!!
Statement statement = con.createStatement();
//要執(zhí)行的SQL語(yǔ)句
String sql = "select * from student";
//3.ResultSet類,用來(lái)存放獲取的結(jié)果集!!
ResultSet rs = statement.executeQuery(sql);
System.out.println("-----------------");
System.out.println("執(zhí)行結(jié)果如下所示:");
System.out.println("-----------------");
System.out.println(" 學(xué)號(hào)" + "\t" + " 姓名");
System.out.println("-----------------");
String name = null;
String id = null;
while(rs.next()){
//獲取stuname這列數(shù)據(jù)
name = rs.getString("stuname");
//獲取stuid這列數(shù)據(jù)
id = rs.getString("stuid");
//首先使用ISO-8859-1字符集將name解碼為字節(jié)序列并將結(jié)果存儲(chǔ)新的字節(jié)數(shù)組中。
//然后使用GB2312字符集解碼指定的字節(jié)數(shù)組。
name = new String(name.getBytes("ISO-8859-1"),"gb2312");
//輸出結(jié)果
System.out.println(id + "\t" + name);
}
rs.close();
con.close();
} catch(ClassNotFoundException e) {
//數(shù)據(jù)庫(kù)驅(qū)動(dòng)類異常處理
System.out.println("Sorry,can`t find the Driver!");
e.printStackTrace();
} catch(SQLException e) {
//數(shù)據(jù)庫(kù)連接失敗異常處理
e.printStackTrace();
}catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}finally{
System.out.println("數(shù)據(jù)庫(kù)數(shù)據(jù)成功獲取!!");
}
}
}
在上面while代碼段后面添加以下代碼段:
String name = null;
String id = null;
while(rs.next()){
//獲取stuname這列數(shù)據(jù)
name = rs.getString("stuname");
//獲取stuid這列數(shù)據(jù)
id = rs.getString("stuid");
//首先使用ISO-8859-1字符集將name解碼為字節(jié)序列并將結(jié)果存儲(chǔ)新的字節(jié)數(shù)組中。
//然后使用GB2312字符集解碼指定的字節(jié)數(shù)組。
name = new String(name.getBytes("ISO-8859-1"),"gb2312");
//輸出結(jié)果
System.out.println(id + "\t" + name);
}
PreparedStatement psql;
ResultSet res;
//預(yù)處理添加數(shù)據(jù),其中有兩個(gè)參數(shù)--“?”
psql = con.prepareStatement("insert into student values(?,?)");
psql.setInt(1, 8); //設(shè)置參數(shù)1,創(chuàng)建id為5的數(shù)據(jù)
psql.setString(2, "xiaogang"); //設(shè)置參數(shù)2,name 為小明
psql.executeUpdate(); //執(zhí)行更新
//預(yù)處理更新(修改)數(shù)據(jù)
psql = con.prepareStatement("update student set stuname = ? where stuid = ?");
psql.setString(1,"xiaowang"); //設(shè)置參數(shù)1,將name改為王五
psql.setInt(2,10); //設(shè)置參數(shù)2,將id為2的數(shù)據(jù)做修改
psql.executeUpdate();
//預(yù)處理刪除數(shù)據(jù)
psql = con.prepareStatement("delete from student where stuid = ?");
psql.setInt(1, 5);
psql.executeUpdate();
//查詢修改數(shù)據(jù)后student表中的數(shù)據(jù)
psql = con.prepareStatement("select*from student");
res = psql.executeQuery(); //執(zhí)行預(yù)處理sql語(yǔ)句
System.out.println("執(zhí)行增加、修改、刪除后的數(shù)據(jù)");
while(res.next()){
name = res.getString("stuname");
id = res.getString("stuid");
name = new String(name.getBytes("ISO-8859-1"),"gb2312");
System.out.println(id + "\t" + name);
}
res.close();
psql.close();
下面是一個(gè)從 mysql 數(shù)據(jù)庫(kù)獲取用戶信息的例子,可以參考一下:
import?java.sql.Connection;
import?java.sql.DriverManager;
import?java.sql.ResultSet;
import?java.sql.SQLException;
import?java.sql.Statement;
import?java.util.ArrayList;
import?java.util.List;
//?用戶類,存儲(chǔ)單個(gè)用戶信息
class?User?{
private?int?id;
private?String?name;
public?User(int?id,?String?name)?{
this.id?=?id;
this.name?=?name;
}
public?int?getId()?{
return?id;
}
public?void?setId(int?id)?{
this.id?=?id;
}
public?String?getName()?{
return?name;
}
public?void?setName(String?name)?{
this.name?=?name;
}
@Override
public?String?toString()?{
return?"User?[id="?+?id?+?",?name="?+?name?+?"]";
}
}
public?class?Demo1?{
public?static?void?main(String[]?args)?throws?ClassNotFoundException,?SQLException?{
//?本例使用?mysql?數(shù)據(jù)庫(kù),演示將數(shù)據(jù)庫(kù)?test?的?tb_users?表中的用戶信息
//?放到?List?中
//?加載數(shù)據(jù)驅(qū)動(dòng)
Class.forName("com.mysql.jdbc.Driver");
//?數(shù)據(jù)庫(kù)連接字符串,?此例數(shù)據(jù)庫(kù)為?test
String?url?=?"jdbc:mysql://localhost:3306/test";
String?user?=?"root";????//?數(shù)據(jù)庫(kù)用戶名
String?password?=?"";????//?數(shù)據(jù)庫(kù)密碼
//?打開(kāi)一個(gè)數(shù)據(jù)連接
Connection?conn?=?DriverManager.getConnection(url,?user,?password);
Statement?stmt?=?conn.createStatement();
//?獲取表?tb_users?所有用戶信息到結(jié)果集中
ResultSet?rs?=?stmt.executeQuery("SELECT?id,?name?FROM?tb_users");
//?定義一個(gè)存放用戶信息的?List
ListUser?users?=?new?ArrayList();
//?提取用戶信息,并將用戶信息放入?List
while?(rs.next())?{
//?獲取用戶ID
int?id?=?rs.getInt(1);
//?獲取用戶名
String?name?=?rs.getString(2);
users.add(new?User(id,?name));
}
rs.close();
stmt.close();
conn.close();
//?顯示用戶信息
for?(User?u?:?users)?{
System.out.println(u);
}
}
}
網(wǎng)站標(biāo)題:java代碼mysql java代碼怎么運(yùn)行
轉(zhuǎn)載來(lái)于:http://www.chinadenli.net/article44/dopjiee.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供App設(shè)計(jì)、關(guān)鍵詞優(yōu)化、手機(jī)網(wǎng)站建設(shè)、網(wǎng)站排名、做網(wǎng)站、網(wǎng)站收錄
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來(lái)源: 創(chuàng)新互聯(lián)