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