“請必須要有自信,你就是一道風景,沒必要在別人風景裏面仰視。”你好,我是夢陽辰,快來和我一起學習吧!
文章目錄
01.JDBC是什麼?
概念:Java DataBase Connectivity ,java數據庫連接,Java語言操作數據庫。
JDBC本質:sun公司定義的一套操作所有關係型數據庫的接口。各個數據庫廠商去實現這套接口(提供數據庫驅動jar包)。我們可以使用這套接口(jdbc)編程,真正執行的代碼時驅動jar包中的實現類。但我們只需要面向接口編程。
02.JDBC快速入門
步驟:
1.下載驅動:去你使用的數據庫廠商的官網找到你要使用的數據庫版本對應的版本驅動,下載驅動。
2.將驅動jar包導入項目
1.賦值mysql-connector-java-5.1.xx-bin.jar到項目的lib目錄下。
然後單擊目錄右鍵–>Add as Library。
3.註冊驅動(告訴程序你用的是哪個廠商,哪個版本的數據庫)
4.獲取數據庫連接對象(Connetion)(表示JVM的進程和數據庫進程之間的通道打開了,這屬於進程之間的通信,重量級的,使用完之後一定要關閉)
5.定義sql
6.獲取執行sql語句的對象(Statement)(專門執行sql語句的對象)
7.執行sql,接受返回結果
8.處理結果
9.釋放連接
注意:用文本編輯器開發,需要配置環境變量到classpath中。
如果使用IDEA工具的時候,不需要配置classpath環境變量,按要求導入jar包到項目即可。
@WebServlet("/com/teaching/case631/JDBC")public class JDBC extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public JDBC() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
request.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=utf-8");
PrintWriter out = response.getWriter();
Connection conn =null;
Statement stat = null;
try {
//1.加載驅動
Class.forName("com.mysql.jdbc.Driver");
//2.設置連接參數,url,user,password
String url = "jdbc:mysql://localhost:3306/teaching";
String user ="root";
String password ="xxxx";
String useUnicode = "true";//設置編碼
String characterEncoding = "UTF8";
/*url="jdbc:mysql://localhost:3306/teaching"
+"?user=root"
+"&password="xxxxx"
+"&userUnicode=true"
+"&characterEncoding=UTF8";
*/
//conn = DriverManager.getConnection(url);
//3.獲取數據庫連接
conn = DriverManager.getConnection(url,user,password);
stat = conn.createStatement();
//5.定義sql語句
String sql = "update student set name = '張三' where name='夢陽辰'";
//6.利用載體執行SQL語句
int count = stat.executeUpdate(sql);
//7.處理返回結果
if(count>0) {
out.print("連接數據庫成功!");
}else {
out.print("連接數據庫失敗!");
}
} catch (ClassNotFoundException | SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
//7.關閉連接
if(stat!=null) {
try {
stat.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if( conn !=null) {
try {
conn.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}}
查詢:
@WebServlet("/com/teaching/case631/JDBC")public class JDBC extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public JDBC() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
request.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=utf-8");
PrintWriter out = response.getWriter();
Connection conn =null;
Statement stat = null;
ResultSet rs = null;
try {
//1.加載驅動
Class.forName("com.mysql.jdbc.Driver");
//2.設置連接參數,url,user,password
String url = "jdbc:mysql://localhost:3306/teaching";
String user ="root";
String password ="0910";
String useUnicode = "true";
String characterEncoding = "UTF8";
//3.獲取數據庫連接
conn = DriverManager.getConnection(url,user,password);
stat = conn.createStatement();
//5.定義sql語句
String sql = "select * from student";
//6.利用載體執行SQL語句
rs = stat.executeQuery(sql);
//7.處理返回結果
while(rs.next()){
int id = rs.getInt("id");
String sequence = rs.getString("sequence");
String name = rs.getString("name");
String sex = rs.getString("sex");
Date birthday = rs.getDate("birthday");
out.println(id+" "+sequence+" " +name+" "+sex+" "+birthday);
}
} catch (ClassNotFoundException | SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
//7.關閉連接
if(rs!=null) {
try {
rs.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(stat!=null) {
try {
stat.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if( conn !=null) {
try {
conn.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}}
03.JDBC中的各個類和接口
JDBC API主要位於java.sql包下。
Dirver接口是所有JDBC驅動程序必須實現的接口,該接口專門提供給數據庫廠商使用。編寫運行程序記得,一定要先將對應數據庫廠商的jar包導入項目的classpath中。
1.DriverManager類(驅動管理對象)
功能:
1).註冊驅動(告訴程序使用哪一個驅動jar)
//註冊與給定的驅動程序 DriverManager static void registerDriver(Driver driver, DriverAction da)
//寫代碼的時候使用:(在驅動5之後可以不寫)
Class.forName("com.mysql.jdbc.Driver");
//將類加載置內存,一些代碼自動執行(靜態代碼塊)
com.mysql.jdbc.Driver的靜態代碼塊:
static {
try {
//真正註冊驅動的程序
java.sql.DriverManager.registerDriver(new Driver());
} catch (SQLException E) {
throw new RuntimeException("Can't register driver!");
}
}
2.)獲取數據庫連接
//嘗試建立與給定數據庫URL的連接static Connection getConnection(String url, String user, String password)
url:
jdbc:mysql:// 協議
127.0.0.1 IP地址
3306 mysql數據庫端口號
teaching 數據庫
如果主機是本機,端口號是3306,則主機ip和端口號可以不寫。
2.Connection接口(數據庫連接對象)
功能:
1).獲取執行sql的對象。
//創建一個 Statement對象,用於將SQL語句發送到數據庫Statement createStatement()
//創建一個 PreparedStatement對象,用於將參數化的SQL語句發送到數據庫PreparedStatement prepareStatement(String sql)
2).事物管理
開啓事務
void setAutoCommit(boolean autoCommit)
將此連接的自動提交模式設置爲給定狀態,false,即爲開啓事務
提交事務
void commit()
回滾事務
void rollback()
3.Statement接口(執行sql的對象)
用於執行靜態SQL語句並返回其生成的結果的對象。
boolean execute(String sql) ;//使用不多
執行給定的SQL語句,這可能會返回多個結果
int executeUpdate(String sql) ;DML語句
執行給定的SQL語句,這可能是 INSERT, UPDATE,或 DELETE語句,
或者不返回任何內容,如SQL DDL(create,alter,drop)語句的SQL語句。
返回值爲影響的行數,可以用來判斷DML語句是否執行成功。
ResultSet executeQuery(String sql) ;
執行給定的SQL(select)語句,該語句返回單個 ResultSet對象。
練習:
1.student表 添加一條記錄
2.student表 修改一條記錄
3.student表 刪除一條記錄
public class JdbcTest2 {
public static void main(String[] args) {
Connection conn = null;
Statement stat = null;
//1.註冊驅動
try {
Class.forName("com.mysql.jdbc.Driver");
//2.獲取連接
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/teaching","root","0910");
//3.獲取執行sql對象
stat = conn.createStatement();
//4.定義sql語句
//String sql = "insert into student(sequence,name,sex,birthday) values('12341234','張三','男','1999-10-18')";
//String sql = "update student set name='李四' where name = '張三'";
String sql = "delete from student where name ='李四'";
//5.執行sql
int count = stat.executeUpdate(sql);
System.out.println(count);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException throwables) {
throwables.printStackTrace();
}finally {
//關閉資源
try {
if(stat!=null){
stat.close();
}
if(conn!=null){
conn.close();
}
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}}
4.ResultSet接口(結果集對象)
表示數據庫結果集的數據表,通常通過執行查詢數據庫的語句生成.
封裝結果集對象:
1.next() //:遊標向下移動一行//獲取數據(只能獲取某行某列的數據,不能獲取整行)參數可以爲列數(從1開始),也可以爲列名2.getXxx(int columnIndex);Xxx代表數據類型。
String getString(int columnIndex) 這個檢索的當前行中指定列的值 ResultSet對象爲 String的Java編程語言。
String getString(String columnLabel) 這個檢索的當前行中指定列的值 ResultSet對象爲 String的Java編程語言。
遍歷結果集:
boolean next() ;//如果有數據返回true,沒有false
public class JdbcTest3 {
public static void main(String[] args) {
Connection conn = null;
Statement stat = null;
ResultSet rs = null;
//1.註冊驅動
try {
Class.forName("com.mysql.jdbc.Driver");
//2.獲取連接
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/teaching","root","0910");
//3.獲取執行sql對象
stat = conn.createStatement();
//4.定義sql語句
//String sql = "insert into student(sequence,name,sex,birthday) values('12341234','張三','男','1999-10-18')";
//String sql = "update student set name='李四' where name = '張三'";
String sql = "select * from student";
//5.執行sql
rs = stat.executeQuery(sql);
//6.處理結果集
//6.1讓遊標向下移動一行
while(rs.next()){
int id = rs.getInt(1);
String name = rs.getString("name");
System.out.println(id+"----"+name);
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException throwables) {
throwables.printStackTrace();
}finally {
//關閉資源
try {
if(rs!=null){
rs.close();
}
if(stat!=null){
stat.close();
}
if(conn!=null){
conn.close();
}
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}}
練習:
定義一個方法,查詢Studnet表的數據將其封裝爲對象,然後裝載集合,返回。
1.定義Student類(一個表就相當於一個類)
2.定義public List findAll(){}
3.實現方法 select xx,xx,xxx from Student;
student類
/**
* javaBean
*/public class Student {
private Integer id;//爲防止數據庫字段爲空,定義爲應用數據類型
private String sequence;
private String name;
private String sex;
private Date birthday;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getSequence() {
return sequence;
}
public void setSequence(String sequence) {
this.sequence = sequence;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
@Override
public String toString() {
return "Student{" +
"id=" + id +
", sequence='" + sequence + '\'' +
", name='" + name + '\'' +
", sex='" + sex + '\'' +
", birthday=" + birthday +
'}';
}}
/**
* 定義一個方法,查詢Studnet表的數據將其封裝爲對象,然後裝載集合,返回
*/public class JdbcTest4 {
public static void main(String[] args) {
List<Student> list= new JdbcTest4().findAll();//對象.方法
System.out.println(list);
System.out.println(list.size());
}
public List<Student> findAll(){
Connection conn = null;
Statement stat = null;
ResultSet rs = null;
List<Student> list = new ArrayList<>();
//1.註冊驅動
try {
Class.forName("com.mysql.jdbc.Driver");
//2.獲取連接
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/teaching","root","0910");
//3.獲取執行sql對象
stat = conn.createStatement();
//4.定義sql語句
String sql = "select id,sequence,name,sex,birthday from student";
//5.執行sql
rs = stat.executeQuery(sql);
//6.處理結果集
//6.1讓遊標向下移動一行
Student student = null;
while (rs.next()){
int id = rs.getInt(1);
String sequence = rs.getString("sequence");
String name = rs.getString("name");
String sex = rs.getString("sex");
Date birthday = rs.getDate("birthday");
//創建student對象,賦初值
student = new Student();
student.setId(id);
student.setSequence(sequence);
student.setName(name);
student.setSex(sex);
student.setBirthday(birthday);
//裝載集合
list.add(student);
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException throwables) {
throwables.printStackTrace();
}finally {
//關閉資源
try {
if(rs!=null){
rs.close();
}
if(stat!=null){
stat.close();
}
if(conn!=null){
conn.close();
}
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
return list;
}}
可以寫JDBC工具類,簡化JDBC連接數據的操作。
採用配置文件,存儲url,user,password等。
04.PreparedStatement接口(Statement的子接口)
Statement對象,執行sql會存在sql注入問題。
'a' or 'a' = 'a'
SQL注入問題:在拼接sql時,有一些sql的特殊關鍵字參與字符串的拼接。會造成安全性問題。
2.解決sql注入問題:使用PreparedStatement對象來解決。
PreparedStatement對象採取預編譯。
SQL語句已預編譯並存儲在PreparedStatement對象中。 然後可以使用該對象多次有效地執行此語句。
參數使用佔位符
步驟:
1.下載驅動:去你使用的數據庫廠商的官網找到你要使用的數據庫版本對應的版本驅動,下載驅動。
2.將驅動jar包導入項目
1.賦值mysql-connector-java-5.1.xx-bin.jar到項目的lib目錄下。
然後單擊目錄右鍵–>Add as Library。
3.註冊驅動(告訴程序你用的是哪個廠商,哪個版本的數據庫)
4.獲取數據庫連接對象(Connetion)(表示JVM的進程和數據庫進程之間的通道打開了,這屬於進程之間的通信,重量級的,使用完之後一定要關閉)
5.定義sql
採取佔位符?
select * from student where username = ? and password =?;
6.獲取執行sql語句的對象(PreparedStatement)(專門執行sql語句的對象)
創建一個 PreparedStatement對象,用於將參數化的SQL語句發送到數據庫
PreparedStatement prepareStatement(String sql)
7.給佔位符賦值
setXxx(參數1,參數2)
參數1:?的位置編碼 從1開始
參數2:值
8.執行sql,接受返回結果(不需要參數sql)
9.處理結果
10.釋放連接
05.JDBC控制事務
JDBC控制事務:
**事務:**一個包含多個步驟的業務操作。如果這個業務操作被事務管理,則這多個步驟要麼同時成功,要麼同時失敗。
2.操作:
開啓事務
提交事務
回滾事務
3.使用connection對象來管理事務
開後事務 : setAutoCommit(boolean autoCcommit) :調用該方法設置參數爲false,即開起事務。
提交事務: commit()
回滾事務: rollback( )
Give up worrying about what others think of you。What they think isn’t important.What is important is how you feel about yourself.
這篇文章也許對你有用: