基本連接
- 加載驅(qū)動(dòng):
Class.forName(com.mysql.jdbc.Driver)
- 建立連接:
Connection conn=DriverManager.getConnection(url,user,password)
其中
url="jdbc:mysql://localhost:3306/java_demo"
,這里的java_demo
是自己創(chuàng)建的數(shù)據(jù)庫(kù)的名字,user
是mysql
數(shù)據(jù)庫(kù)的管理員,password
是密碼
下面直接連接數(shù)據(jù)庫(kù),返回的是接口Connection對(duì)象
import java.sql.*;
public static Connection getConnection()
{
Connection conn;
String driver="com.mysql.jdbc.Driver"; //驅(qū)動(dòng)名稱(chēng)
String url="jdbc:mysql://localhost:3306/java_demo"; //url
String user="root";
String password="root"; //管理員和密碼都是root
try{
Class.forName(driver); //加載驅(qū)動(dòng),但是會(huì)有ClassNotFoundException異常,因此要避免異常
try{
conn = Dri verManager.getConnection(url, user, password); //獲得數(shù)據(jù)庫(kù)連接
return conn; //返回conn
}catch(SQLException e)
{
e.printStackTrace();
}
}catch (ClassNotFoundException e) {
e.printStackTrace();
}
return null; //如果出現(xiàn)異常就會(huì)返回null
}
```
## 查詢(xún)數(shù)據(jù)
>* **首先根據(jù)所得的`Connection`對(duì)象創(chuàng)建`Statement`對(duì)象:`Statement statement = connection.createStatement()`;**
>* **寫(xiě)查詢(xún)語(yǔ)句:`String sql="select * from student;" `這里是查詢(xún)所有student中的數(shù)據(jù),詳細(xì)內(nèi)容請(qǐng)看我的[SQL干貨篇二](https://chenjiabing666.github.io/2017/04/09/SQL%E5%B9%B2%E8%B4%A7%E7%AF%87%E4%BA%8C/)**
>* **創(chuàng)建ResultSet對(duì)象存儲(chǔ)查詢(xún)結(jié)果:`ResultSet res=statement.executeQuery(sql)`,詳細(xì)的內(nèi)容請(qǐng)看[官方文檔ResultSet詳細(xì)用法](http://tool.oschina.net/uploads/apidocs/jdk-zh/java/sql/ResultSet.html)**
**代碼**
```java
String sql="select * from student";
if(!conn.isClosed())
{
Statement statement=conn.createStatement(); //這里的conn是上面連接數(shù)據(jù)庫(kù)的返回的Connection對(duì)象
ResultSet res=statement.executeQuery(sql); //執(zhí)行查詢(xún),注意這里只能是executeQuery,Statement還有一些執(zhí)行mysql函數(shù),但是都不適合查詢(xún),后面會(huì)詳細(xì)說(shuō)
while(res.next()) //如果res結(jié)果中還有元素,那么返回true,否則返回的是false,用來(lái)判斷是否res中還有結(jié)果
{
int id=res.getInt("id"); //得到id,這里的id是student表中的屬性名 對(duì)應(yīng)的時(shí)int BigInt smallint.....
String name=res.getString("name"); //得到姓名,對(duì)應(yīng)的是mysql中的Char varChar類(lèi)型
}
}
```
>**當(dāng)然上面只是對(duì)于基本的查詢(xún)數(shù)據(jù),在一些項(xiàng)目中根本用不到,因?yàn)椴惶`活,上面的方法只適合全局查詢(xún),并不適合在項(xiàng)目中根據(jù)條件查詢(xún),下面介紹預(yù)編譯sql語(yǔ)句的接口[PrepareStatement](http://tool.oschina.net/uploads/apidocs/jdk-zh/java/sql/PreparedStatement.html)**
>* **首先編寫(xiě)sql語(yǔ)句:`sql="select * from student where id=?;";`,這里的`?`表示一個(gè)占位,將條件在后面給出,但是這里一定要用`?`**
>* **創(chuàng)建對(duì)象:`PrepareStatement pre=conn.preparestatement(sql);`這里傳入?yún)?shù)`sql`**
>* **設(shè)置`sql`中的條件語(yǔ)句,填補(bǔ)占位`?`的值:pre.setInt(1,1);這里的`SetInt`設(shè)置`id`值的為1,因?yàn)檫@的`id`是`int`類(lèi)型的,第一個(gè)參數(shù)是表示`prepareindex`,就是表示第一個(gè)占位`?`,當(dāng)然第二個(gè)就是2,其中還有`SetString(prepareindex String var)`,用來(lái)給定表中的`char`后者`varchar`類(lèi)型的值**
>**代碼:**
```java=
if(!connection.isClosed())
{
String sql="select * from course where id=?,name=?";
PreparedStatement preparedStatement=connection.prepareStatement(sql);
preparedStatement.setInt(1,1); //給定條件中的值
prepareStatement.setString(2,"jack"); //為第二個(gè)?賦值
ResultSet res=preparedStatement.executeQuery(); //執(zhí)行查詢(xún),返回的仍然是ResultSet對(duì)象
while(res.next())
{
int id=res.getInt("id");
String name=res.getString("name");
System.out.println(id+"--"+name);
}
}
```
## 插入數(shù)據(jù)
>**插入數(shù)據(jù)和上面的兩種方法基本是一樣的,不同的是`mysql`語(yǔ)句不同,還有的就是執(zhí)行語(yǔ)句改成了`executeUpdate(sql)`,下面的代碼值給出了預(yù)編譯對(duì)象的方法,另外一種的方法使用范圍并不是很大,只要把上面的查詢(xún)改為`executeUpdate`即可**
>**代碼:**
```java
public static int save(MemoBean memo) {
String sql = "insert into student (username, title, content, momotype, memotime) values (?, ?, ?, ?, ?);";
Connection conn = getConnection();
PreparedStatement ps = null;
try {
ps = conn.prepareStatement(sql);
ps.setString(1, memo.getUsername()); //設(shè)值value中的值
ps.setString(2, memo.getTitle());
ps.setString(3, memo.getContent());
ps.setString(4, memo.getMemotype());
ps.setString(5, memo.getMemotime());
return ps.executeUpdate(); //這里使用的是excuteUpdate
} catch (SQLException e) {
e.printStackTrace();
} finally {
if (ps != null) {
try {
ps.close(); //關(guān)閉預(yù)編譯對(duì)象
} catch (SQLException e) {
e.printStackTrace();
}
}
if (conn != null) {
try {
conn.close(); //關(guān)閉Connection對(duì)象
} catch (SQLException e) {
e.printStackTrace();
}
}
}
return -1; //沒(méi)有插入成功返回-1
}
更新數(shù)據(jù)
這里是同樣的思路,和插入的基本是一樣,只需要改變sql語(yǔ)句即可
代碼:
public static int update(MemoBean memo) {
String sql = "update student set username=?,title=?,content=?,momotype=?,memotime=? where id=?;";//查詢(xún)語(yǔ)句
Connection connection = getConnection();
PreparedStatement ps = null;
try {
ps = connection.prepareStatement(sql);
ps.setString(1, memo.getUsername()); //設(shè)置條件語(yǔ)句中的值
ps.setString(2, memo.getTitle());
ps.setString(3, memo.getContent());
ps.setString(4, memo.getMemotype());
ps.setString(5, memo.getMemotime());
ps.setInt(6,memo.getId());
return ps.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
finally {
if(ps!=null)
{
try {
ps.close();
}catch (SQLException e)
{
e.printStackTrace();
}
}
if(connection!=null)
{
try {
connection.close();
}catch (SQLException e)
{
e.printStackTrace();
}
}
}
return -1;
}
最后說(shuō)
- 上面的代碼是從自己項(xiàng)目中截取的一部分代碼,這個(gè)是比較適用于面向?qū)ο蟮模彩亲畛S玫膶?duì)于目前來(lái)看
- 上面只是給出了查詢(xún),插入,更新,因?yàn)檫@是最常用到的方法,其中還有創(chuàng)建表,刪除表,當(dāng)然還有一些他的,這里的創(chuàng)建表直接用
execute(sql)
即可執(zhí)行,刪除表也是用execute(sql)
即可執(zhí)行,當(dāng)然如果要按照指定的條件刪除,那么可以使用預(yù)編譯對(duì)象執(zhí)行
- 其中
executeUpdate(sql)
適用于create
,insert
,update
,delete
,但是executeQuery(sql)
適用于select
,具體見(jiàn)官方文檔