JDBC操作步骤及数据库连接操作

 

一、JDBC操作步骤

1.加载数据库驱动程序:各个数据库都会提供JDBC的驱动程序开发包,直接把JDBC操作所需要的开发包(一般为*.jar或*.zip)直接配置到classpath路径即可。

2.连接数据库:根据各个数据库的不同连接的地址也不同,此连接地址将由数据库厂商提供,一般在使用JDBC连接数据库的时候都要求用户输入数据库连接的用户名和密码,用户在取得连接之后才可以对数据库进行查询或更新的操作。

3.使用语句进行数据库操作:数据库操作分为更新和查询两种操作,除了可以使用标准的SQL语句之外,对于各个数据库也可以使用其自己提供的各种命令。

4.关闭数据库连接:数据库操作完毕之后需要关闭连接以释放资源。

 

二、配置数据库的驱动程序

1.下载驱动:http://www.mysql.com/downloads/connector/j/

2.配置环境变量:在classpath中添加驱动路径(例如我的路径是D:\MySQL-connector-Java-5.1.21-bin.jar;);

 

三、加载驱动

 

  1. public class connector {  
  2.     public static final String DBDRIVER = "org.gjt.mm.mysql.Driver";   //定义MySQL数据库驱动程序  
  3.     public static void main(String[] args) {  
  4.         try {  
  5.             Class.forName(DBDRIVER); //加载驱动程序  
  6.         } catch (ClassNotFoundException e) {  
  7.             e.printStackTrace();  
  8.         }  
  9.     }  
  10. }  
public class connector {
	public static final String DBDRIVER = "org.gjt.mm.mysql.Driver";   //定义MySQL数据库驱动程序
	public static void main(String[] args) {
		try {
			Class.forName(DBDRIVER); //加载驱动程序
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
	}
}

四、连接及关闭数据库

 

1.使用DriverManager类进行连接操作,DriverManager类的常用方法:

       (1)通过连接地址连接数据库

                public static Connection getConnection(String url) throws SQLException

       (2)通过连接地址连接数据库同时输入用户名和密码

                public static Connection getConnection(String url, String user, String password) throws SQLException

2.DriverManager说明:

(1)在DriverManager中,提供的主要操作是得到一个数据库的连接,getConnection()方法就是取得连接对象,此方法返回的类型是Connection对象,不管使用那种方式连接,都必须提供一个数据库的连接地址,如果在连接数据库的时候需要用户名和密码,则还需要将用户名和密码设置上。MySQL数据库的连接地址格式如下:jdbc:mysql://IP地址:端口号/数据库名称

(2)数据库连接地址的形式由三部分组成:

       a.jdbc协议:JDBC URL中的协议总是jdbc;

       b.子协议:驱动程序名和数据库连接机制(这种机制可由一个或多个驱动程序支持)的名称,例如:mysql;

       c.子名称:一种标识数据库的方法。必须遵循"/主机名:端口/子协议"的标准URL命名约定,例如://localhost:3306/Joywy.

3.Connection

通过DriverManager取得Connection对象之后,实际上就表示数据库连接上了,连接上数据库之后就可以进行数据库的更新及查询操作,但是操作的最后数据库的连接必须关闭。

连接数据库代码如下:

 

  1. import java.sql.Connection;  
  2. import java.sql.DriverManager;  
  3. import java.sql.SQLException;  
  4.   
  5. public class ConnectionDemo{  
  6.     //定义MySQL驱动程序  
  7.     public static final String DBDRIVER = "org.gjt.mm.mysql.Driver";  
  8.     //定义MySQL数据库的连接地址  
  9.     public static final String DBURL = "jdbc:mysql://localhost:3306/xiaowei";  
  10.     //MySQL数据库的连接用户名  
  11.     public static final String DBUSER = "root";  
  12.     //MySQL数据库的连接密码  
  13.     public static final String DBPASS = "android";  
  14.     public static void main(String[] args){  
  15.         //数据库连接  
  16.         Connection con = null;  
  17.         try{  
  18.             //加载驱动  
  19.             Class.forName(DBDRIVER);  
  20.         }catch(ClassNotFoundException e){  
  21.             e.printStackTrace();  
  22.         }  
  23.         try{  
  24.             con = DriverManager.getConnection(DBURL, DBUSER, DBPASS);  
  25.         }catch(SQLException e){  
  26.             e.printStackTrace();  
  27.         }  
  28.         System.out.println(con);  
  29.         try{  
  30.             //数据库关闭  
  31.             con.close();  
  32.         }catch(SQLException e){  
  33.             e.printStackTrace();  
  34.         }  
  35.     }  
  36. }  
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class ConnectionDemo{
	//定义MySQL驱动程序
	public static final String DBDRIVER = "org.gjt.mm.mysql.Driver";
	//定义MySQL数据库的连接地址
	public static final String DBURL = "jdbc:mysql://localhost:3306/xiaowei";
	//MySQL数据库的连接用户名
	public static final String DBUSER = "root";
	//MySQL数据库的连接密码
	public static final String DBPASS = "android";
	public static void main(String[] args){
		//数据库连接
		Connection con = null;
		try{
			//加载驱动
			Class.forName(DBDRIVER);
		}catch(ClassNotFoundException e){
			e.printStackTrace();
		}
		try{
			con = DriverManager.getConnection(DBURL, DBUSER, DBPASS);
		}catch(SQLException e){
			e.printStackTrace();
		}
		System.out.println(con);
		try{
			//数据库关闭
			con.close();
		}catch(SQLException e){
			e.printStackTrace();
		}
	}
}

五、数据库操作

 

1.Statement接口

此接口通过使用Connection接口中的createStatement()方法实例化,此接口定义了一下方法:

 

No.

方法

类型

描述

1

Int executeUpdate(String sql)throws SQLException

普通

执行数据库更新的SQL语句,例如:INSERT、UPDATE、DELETE等语句,返回更新的记录数

2

ResultSet executeQuery(String sql)throws SQLException

普通

执行数据库查询操作,返回一个结果集对象

3

void addBatch(String sql)throws SQLException

普通

增加一个待执行的SQL语句

4

int[] executeBatch()throws SQLException

普通

批量执行SQL语句

5

void close()throws SQLException

普通

关闭Statement操作

6

Boolean execute(String sql)throws SQLException

普通

执行SQL语句

2.ResultSet接口

 

使用SQL中的SELECT语句可以将数据库的全部结果查询出来,在JDBC的操作中数据库的所有查询记录将使用ResultSet进行接收,并使用ResultSet显示内容。

3.PreparedStatement接口

PreparedStatement接口是Statement的子接口,属于预处理操作,与直接使用Statement不同的是,PreparedStatement在操作时,是先在数据表之中准备好一条SQL语句,但是此SQL语句的具体内容暂时不设置,而是之后再进行设置,以插入数据为例,使用PreparedStatement插入数据时,数据表中的指针首先指向最后一条数据之后,但是里面的内容是不知道的,而是等待用户分别设置的。

注意:设置日期格式的问题,在PreparedStatement中定义了setData(),此方法可以设置日期内容,但是此方法使用时,后面的Data类型变量是java.sql.Data,而不是java.util.Data,所以如果要想将一个java.util.Data类型的内容变为java.sql.Date类型的内容应该使用如下的语句形式:

 

  1.               String birthday = "2007-08-27"        //生日  
  2. java.util.Date temp = null;         //声明一个Date对象  
  3. //通过SimpleDataFormat类将一个字符串变为java.util.Date类型  
  4. temp = new SimpleDataFormat("yyyy-MM-dd").parse(birthday);  
  5. //通过java.util.Data取出具体的日期数,并将其变为java.sql.Data类型  
  6. java.sql.Data bir = new java.sql.Data(temp.getTime());  
                String birthday = "2007-08-27"		//生日
		java.util.Date temp = null;			//声明一个Date对象
		//通过SimpleDataFormat类将一个字符串变为java.util.Date类型
		temp = new SimpleDataFormat("yyyy-MM-dd").parse(birthday);
		//通过java.util.Data取出具体的日期数,并将其变为java.sql.Data类型
		java.sql.Data bir = new java.sql.Data(temp.getTime());
 

 

 

代码如下:

DBHelper.java

 

  1. import java.sql.Connection;  
  2. import java.sql.DriverManager;  
  3. import java.sql.PreparedStatement;  
  4. import java.sql.ResultSet;  
  5. import java.sql.SQLException; 
  6. import java.util.ArrayList;  
  7. import java.util.List;  
  8.   
  9.   
  10. public class DBHelper {  
  11.     public static final String DBDRIVER = "com.mysql.jdbc.Driver";  
  12.     public static final String DBURL = "jdbc:mysql://localhost:3306/test";  
  13.     public static final String DBUSER = "root";  
  14.     public static final String DBPASS = "1111";  
  15.       
  16.     public static Connection getConnection(){  
  17.         Connection conn = null;  
  18.         try {  
  19.             Class.forName(DBDRIVER);  
  20.             conn = DriverManager.getConnection(DBURL, DBUSER, DBPASS);  
  21.         } catch (Exception e) {  
  22.             e.printStackTrace();  
  23.         }  
  24.         return conn;  
  25.     }   
  26.       
  27.     public static void save(){  
  28.         Connection con = getConnection();  
  29.         String sql = "insert into Info values(?, ?, ?)";  
  30.         PreparedStatement psmt = null;  
  31.         try {  
  32.             psmt = con.prepareStatement(sql);  
  33.             psmt.setString(1, "123");  
  34.             psmt.setString(2, "12");  
  35.             psmt.setInt(3, 3);  
  36.             int count = psmt.executeUpdate();  
  37.         } catch (Exception e) {  
  38.             e.printStackTrace();  
  39.         }finally{  
  40.             if(psmt != null){  
  41.                 try {  
  42.                     psmt.close();  
  43.                 } catch (SQLException e) {  
  44.                     e.printStackTrace();  
  45.                 }  
  46.             }  
  47.             if(con != null){  
  48.                 try {  
  49.                     con.close();  
  50.                 } catch (SQLException e) {  
  51.                     e.printStackTrace();  
  52.                 }  
  53.             }  
  54.         }  
  55.     }  
  56.       
  57.     public static void delete(){  
  58.         Connection con = getConnection();  
  59.         String sql = "delete from Info where id=?";  
  60.         PreparedStatement psmt = null;  
  61.         try {  
  62.             psmt = con.prepareStatement(sql);  
  63.             psmt.setString(1, "10330070");  
  64.             int count = psmt.executeUpdate();  
  65.         } catch (Exception e) {  
  66.             e.printStackTrace();  
  67.         }finally{  
  68.             if(psmt != null){  
  69.                 try {  
  70.                     psmt.close();  
  71.                 } catch (SQLException e) {  
  72.                     // TODO Auto-generated catch block  
  73.                     e.printStackTrace();  
  74.                 }  
  75.             }  
  76.             if(con != null){  
  77.                 try {  
  78.                     con.close();  
  79.                 } catch (SQLException e) {  
  80.                     // TODO Auto-generated catch block  
  81.                     e.printStackTrace();  
  82.                 }  
  83.             }  
  84.         }  
  85.     }  
  86.       
  87.     public static void update(){  
  88.         Connection con = getConnection();  
  89.         String sql = "update Info set age = ? where id = ?";  
  90.         PreparedStatement psmt = null;  
  91.         try {  
  92.             psmt = con.prepareStatement(sql);  
  93.             psmt.setInt(1, 22);  
  94.             psmt.setString(2, "111313");  
  95.             int count = psmt.executeUpdate();  
  96.         } catch (Exception e) {  
  97.             e.printStackTrace();  
  98.         }finally{  
  99.             if(psmt != null){  
  100.                 try {  
  101.                     psmt.close();  
  102.                 } catch (SQLException e) {  
  103.                     e.printStackTrace();  
  104.                 }  
  105.             }  
  106.             if(con != null){  
  107.                 try {  
  108.                     con.close();  
  109.                 } catch (SQLException e) {  
  110.                     e.printStackTrace();  
  111.                 }  
  112.             }  
  113.         }  
  114.     }  
  115.       
  116.     public static List<Info> query(){  
  117.         List<Info> list = new ArrayList<Info>();  
  118.         Connection con = getConnection();  
  119.         String sql = "select * from Info";  
  120.         PreparedStatement psmt = null;  
  121.         ResultSet rs = null;  
  122.           
  123.         try {  
  124.             psmt = con.prepareStatement(sql);  
  125.             rs = psmt.executeQuery();  
  126.               
  127.             while(rs.next()){    //依次取出数据  
  128.                 Info info = new Info();  
  129.                 info.setId(rs.getString("id"));  
  130.                 info.setPass(rs.getString("pass"));  
  131.                 info.setAge(rs.getInt("age"));  
  132.                 System.out.println(info.getId() +"\t" + info.getPass() + "\t" + info.getAge());  
  133.                 list.add(info);  
  134.             }  
  135.         } catch (Exception e) {  
  136.             e.printStackTrace();  
  137.         }finally{  
  138.             if(rs != null){  
  139.                 try {  
  140.                     rs.close();  
  141.                 } catch (SQLException e) {  
  142.                     e.printStackTrace();  
  143.                 }  
  144.             }  
  145.             if(psmt != null){  
  146.                 try {  
  147.                     psmt.close();  
  148.                 } catch (SQLException e) {  
  149.                     e.printStackTrace();  
  150.                 }  
  151.             }  
  152.             if(con != null){  
  153.                 try {  
  154.                     con.close();  
  155.                 } catch (SQLException e) {  
  156.                     e.printStackTrace();  
  157.                 }  
  158.             }  
  159.         }  
  160.         return list;  
  161.     }  
  162.       
  163.     public static void main(String[] args){  
  164.         System.out.println(query().get(0).getAge());  
  165.           
  166.     }  
  167. }  
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;


public class DBHelper {
	public static final String DBDRIVER = "com.mysql.jdbc.Driver";
	public static final String DBURL = "jdbc:mysql://localhost:3306/test";
	public static final String DBUSER = "root";
	public static final String DBPASS = "1111";
	
	public static Connection getConnection(){
		Connection conn = null;
		try {
			Class.forName(DBDRIVER);
			conn = DriverManager.getConnection(DBURL, DBUSER, DBPASS);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return conn;
	} 
	
	public static void save(){
		Connection con = getConnection();
		String sql = "insert into Info values(?, ?, ?)";
		PreparedStatement psmt = null;
		try {
			psmt = con.prepareStatement(sql);
			psmt.setString(1, "123");
			psmt.setString(2, "12");
			psmt.setInt(3, 3);
			int count = psmt.executeUpdate();
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			if(psmt != null){
				try {
					psmt.close();
				} catch (SQLException e) {
					e.printStackTrace();
				}
			}
			if(con != null){
				try {
					con.close();
				} catch (SQLException e) {
					e.printStackTrace();
				}
			}
		}
	}
	
	public static void delete(){
		Connection con = getConnection();
		String sql = "delete from Info where id=?";
		PreparedStatement psmt = null;
		try {
			psmt = con.prepareStatement(sql);
			psmt.setString(1, "10330070");
			int count = psmt.executeUpdate();
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			if(psmt != null){
				try {
					psmt.close();
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			if(con != null){
				try {
					con.close();
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
	}
	
	public static void update(){
		Connection con = getConnection();
		String sql = "update Info set age = ? where id = ?";
		PreparedStatement psmt = null;
		try {
			psmt = con.prepareStatement(sql);
			psmt.setInt(1, 22);
			psmt.setString(2, "111313");
			int count = psmt.executeUpdate();
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			if(psmt != null){
				try {
					psmt.close();
				} catch (SQLException e) {
					e.printStackTrace();
				}
			}
			if(con != null){
				try {
					con.close();
				} catch (SQLException e) {
					e.printStackTrace();
				}
			}
		}
	}
	
	public static List<Info> query(){
		List<Info> list = new ArrayList<Info>();
		Connection con = getConnection();
		String sql = "select * from Info";
		PreparedStatement psmt = null;
		ResultSet rs = null;
		
		try {
			psmt = con.prepareStatement(sql);
			rs = psmt.executeQuery();
			
			while(rs.next()){    //依次取出数据
				Info info = new Info();
				info.setId(rs.getString("id"));
				info.setPass(rs.getString("pass"));
				info.setAge(rs.getInt("age"));
				System.out.println(info.getId() +"\t" + info.getPass() + "\t" + info.getAge());
				list.add(info);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			if(rs != null){
				try {
					rs.close();
				} catch (SQLException e) {
					e.printStackTrace();
				}
			}
			if(psmt != null){
				try {
					psmt.close();
				} catch (SQLException e) {
					e.printStackTrace();
				}
			}
			if(con != null){
				try {
					con.close();
				} catch (SQLException e) {
					e.printStackTrace();
				}
			}
		}
		return list;
	}
	
	public static void main(String[] args){
		System.out.println(query().get(0).getAge());
		
	}
}

Info.java

 

 

  1. public class Info {  
  2.     private String id;  
  3.     private String pass;  
  4.     private int age;  
  5.     public String getId() {  
  6.         return id;  
  7.     }  
  8.     public void setId(String id) {  
  9.         this.id = id;  
  10.     }  
  11.     public String getPass() {  
  12.         return pass;  
  13.     }  
  14.     public void setPass(String pass) {  
  15.         this.pass = pass;  
  16.     }  
  17.     public int getAge() {  
  18.         return age;  
  19.     }  
  20.     public void setAge(int age) {  
  21.         this.age = age;  
  22.     }  
  23. }  
public class Info {
	private String id;
	private String pass;
	private int age;
	public String getId() {
		return id;
	}
	public void setId(String id) {
		this.id = id;
	}
	public String getPass() {
		return pass;
	}
	public void setPass(String pass) {
		this.pass = pass;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
}
注:

 

(1)一般来说,我会习惯使用PreparedStatement对数据库进行操作。PreparedStatement是预编译方式的,在执行SQL语句的时候效率就要高一些,还有就是PreparedStatement可以更好地避免SQL注入问题;在拼接sql语句时,采用PreparedStatement可以有效地减少出错的几率;PreparedStatement是Statement的一个子类,理所当然地PreparedStatement对Statement有一定的扩展,在性能方面有一定的提高。

(2)在开发中是不能直接使用"SELECT * FROM user",因为这样在查询的时候并不能明确的表示要取的内容是什么,所以开发中查询时肯定要明确地写出需要查找的列。

参考:https://github.com/dwqs/blog/issues/17


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

寅灯

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值