JDBCjava数据库连接技术
JDBC技术
JDBC全称:java DataBase Connectivity,java数据库连接技术。Jdbc是一种接口,用来连接数据库,而接口是实现类是由数据库厂商提供的,我们只需要学习jdbc接口即可,不必关心实现类。针对不同的数据库,厂商提供不同的实现类。
连接步骤:
1. 注册驱动
2. 创建连接
3. 创建语句
4. 执行SQL语句
jdbc四个核心对象原理分析图:
四个核心对象:
DriverManager:publicclass DriverManagerextends Object。是一个类。
管理驱动,管理一组 JDBC 驱动程序的基本服务。在调用 getConnection 方法时,DriverManager 会试着从初始化时加载的那些驱动程序以及使用与当前 applet 或应用程序相同的类加载器显式加载的那些驱动程序中查找合适的驱动程序。
主要方法:
第一种方法传入URL时,将user和password拼接进去,?表示参数起点,多个键值对用&连接。
第二种方法是配置数据库连接文件时使用的,这种方法灵活。传入的第二个参数是属性集(Properties)对象,然后使用它的load方法读取输入流中的数据(使用load方法时,需要传入普通输入流对象),没有返回值,读取完成之后,可以使用它的getProperties(String key)方法获取对应的属性值。
Properties:
publicclass Properties extends Hashtable<Object,Object>:Properties 类表示了一个持久的属性集。Properties 可保存在流中或从流中加载。属性列表中每个键及其对应值都是一个字符串。
主要方法:
public voidload(InputStream inStream) throws IOException从输入流中读取属性列表(键和元素对)。
public voidlist(PrintWriter out)将属性列表输出到指定的输出流。传入一个PrintWriter类型(是一个普通类)的对象(public PrintWriter(File file) throws FileNotFoundException)。该方法表示写入到某个流中。
publicString getProperty(String key)用指定的键在此属性列表中搜索属性。传入的参数是键,返回对应的值。
Connection:是一个接口。
主要方法:
Statement createStatement() throws SQLException:创建一个 Statement 对象来将 SQL 语句发送到数据库。不带参数的 SQL 语句通常使用 Statement 对象执行。返回一个新的Statement对象。
PreparedStatementprepareStatement(String sql) throws SQLException:创建一个 PreparedStatement 对象来将参数化的 SQL 语句发送到数据库。参数sql可能包含一个或多个 '?' IN 参数占位符的 SQL 语句,返回包含预编译SQL语句的新的默认PreparedStatement对象。然后使用PreparedStatement的set系列方法,将数据注入数据库。
PreparedStatement:是一个接口。
主要方法:
void setDate(intparameterIndex,Date x) throws SQLException:传入的参数Date对象是sql包下的Date。第一个参数是指表中的第几列,索引从1开始,索引对应的是第几个问号。
void setInt(intparameterIndex,int x) throws SQLException将指定参数设置为给定 Java int 值。在将此值发送到数据库时,驱动程序将它转换成一个 SQL INTEGER 值。
void setString(intparameterIndex,String x) throws SQLException将指定参数设置为给定 Java String 值。在将此值发送给数据库时,驱动程序将它转换成一个 SQL VARCHAR 或 LONGVARCHAR 值(取决于该参数相对于驱动程序在 VARCHAR 值上的限制的大小)。
执行查询的方法:PreparedStatement在执行时不需要传参数,而Statement在执行语句时需要传入参数(SQL语句)。
Statement:是一个接口。
主要方法:
ResultSetexecuteQuery(String sql) throws SQLException:执行给定的 SQL 语句,该语句返回单个 ResultSet 对象。用于执行查询语句,返回值是结果集。
int executeUpdate(String sql) throws SQLException:执行给定 SQL 语句,该语句可能为 INSERT、UPDATE 或 DELETE 语句,或者不返回任何内容的 SQL 语句(如 SQL DDL 语句)。 用于执行增删改语句,返回的是受影响的行数。
booleanexecute(String sql) throws SQLException:执行给定的 SQL 语句,该语句可能返回多个结果。因为执行的SQL语句可能是查询语句,也可能是增删改语句,那么他们的返回结果是不一样的,所以,如果第一个结果是结果集,就返回true,如果第一个结果是更新行数或者不存在任何结果(比如建表),则返回false。Execute方法执行SQL语句并指示第一个结果的形式。然后,必须使用getResultSet或getUpdateCount来获取结果。
ResultSet:
是一个接口。ResultSet 对象具有指向其当前数据行的光标。最初,光标被置于第一行之前。next 方法将光标移动到下一行;因为该方法在 ResultSet 对象没有下一行时返回 false,所以可以在 while 循环中使用它来迭代结果集。
主要方法:
boolean next() throwsSQLException将光标从当前位置向前移一行。ResultSet光标最初位于第一行之前;第一次调用 next 方法使第一行成为当前行;第二次调用使第二行成为当前行,依此类推。如果新的当前行有效,则返回 true;如果不存在下一行,则返回 false。
void close() throwsSQLException立即释放此ResultSet 对象的数据库和 JDBC 资源,而不是等待该对象自动关闭时发生此操作。
一系列get方法:
int getInt(int columnIndex) :以 Java 编程语言中 int 的形式获取此 ResultSet 对象的当前行中指定列的值。
int getInt(String columnLabel) :以 Java 编程语言中 int 的形式获取此 ResultSet 对象的当前行中指定列的值。
double getDouble(int columnIndex) :以 Java 编程语言中 double 的形式获取此 ResultSet 对象的当前行中指定列的值。
double getDouble(String columnLabel) :以 Java 编程语言中 double 的形式获取此 ResultSet 对象的当前行中指定列的值。
Date getDate(int columnIndex) :以 Java 编程语言中 java.sql.Date 对象的形式获取此 ResultSet 对象的当前行中指定列的值。
Date getDate(String columnLabel) :以 Java 编程语言中的 java.sql.Date 对象的形式获取此 ResultSet 对象的当前行中指定列的值。
Date:
我们一般在导入Date包时导入的是util包下的Date,因为我们在实际应用中,从用户处获得的日期可能是一个字符串,我们需要对字符串进行解析,格式化,而sql包下的Date不能进行解析, 所以我们一般导入util包下的Date,解析之后,可以用sql包下的Date的构造方法(先用util包下的Date的getTime()方法转为long类型,再将long类型的值作为sql包下的Date的有参构造方法的参数传入,就可以获得sql包下的Date对象)。
用户输入的字符串形式的日期是String格式的(String s),我们需要创建日期格式化对象(SimpleDateFormat df),日期格式化对象通过parse方法将字符串字符串s转为util下的Date对象(java.util.Date d),该Date对象d再通过getTime()方法将Date对象d转为long类型的毫秒数(long l),创建sql下的Date对象,使用有参构造方法将long类型的l作为参数传入,这样就成功地将util包下的Date转为sql下的Date。
或者可以使用sql包下的静态方法valueOf(),直接用类名调用,将字符串格式的日期转为sql下的Date对象,但是要注意vaalueOf()里面的String必须是yyyy-mm-dd 形式的日期的 String 对象。否则报错。
Sql下的Date类:
构造方法:
public Date(long date)使用给定毫秒时间值构造一个 Date 对象。
主要方法:
public static Date valueOf(String s):参数:s - 表示 "yyyy-mm-dd" 形式的日期的 String 对象,返回:表示给定日期的 java.sql.Date 对象。
代码示例:
public class Lianxi1 {
publicstatic void main(String[] args) throws ClassNotFoundException, SQLException,IOException {
FileInputStreamf = new FileInputStream("db.properties");//配置文件在项目根目录下,如果不是在根目录下,此处文件路径名要注意从项目根目录开始
//第三步:创建属性集对象,读取文件键值列表
Propertiesp = new Properties();//创建对象
p.load(f);
Class.forName(p.getProperty("driver"));//加载驱动(使用配置文件的方式),创建连接用第三种创建方式时
//Class.forName("com.mysql.jdbc.Driver");//不使用配置文件时的注册驱动方式
//注册驱动的第二种方式:(我们一般不用这种方式,因为该方法在传入参数时,传入的Driver对象在jar包中可以看到它已经注册了一次驱动,总共注册了两次驱动)
//DriverManager.registerDriver(newcom.mysql.jdbc.Driver());//需要传入一个Driver对象,
//创建连接方式一
/*Stringurl ="jdbc:mysql://localhost:3306/wyh?user=root&password=1234";//创建URL,将user和password也传进去,?表示参数的起点,多个参数用&连接。
Connectionc = DriverManager.getConnection(url);//创建连接
*/
//创建连接方式二
//Connectionc = DriverManager.getConnection("jdbc:mysql://localhost:3306/wyh","root", "1234");//三参方法,分别传入URL,user,password
//创建连接方式三,需要在项目中新建一个配置文件,然后读入文件中的键值
//第一步:创建db.properties文件,配置user,password,url,driver
//第二步:创建读入流对象
/*FileInputStreamf = new FileInputStream("db.properties");//配置文件在项目根目录下,如果不是在根目录下,此处文件路径名要注意从项目根目录开始
//第三步:创建属性集对象,读取文件键值列表
Propertiesp = new Properties();//创建对象
p.load(f);*///传入普通输入流,调用load方法,从输入流中读取属性列表,没有返回值,读取完属性列表之后就可以使用getProperties(String key)方法,传入键,返回对应的值
Connectionc = DriverManager.getConnection(p.getProperty("url"), p);//两参方法,第一个参数是URL,通过getProperties方法获取配置文件中的URL值,第二个参数是Properties对象
//使用第三种创建连接方式时,应该把第二步和第三步写在注册驱动之前,因为使用配置文件的方式连接数据库时,我们在加载驱动的时候是通过读取配置文件中的driver键获得值的,所以必须在properties对象调用load方法之后,读取了输入流之后才能获得值。
Statements = c.createStatement();//创建语句
ResultSet set = s.executeQuery("select * from school");
while(set.next()){//遍历结果集
System.out.println("编号:"+set.getString("id")+" 姓名:"+set.getString("name")+" 课程编号:"+set.getString("score")+" 成绩:"+set.getDouble("score")+" 民族:"+set.getString("minzu"));
}
set.close();
}
}
public class Lianxi2 {
publicstatic void main(String[] args) throws ClassNotFoundException {
Connectionc = null;
Statements = null;
ResultSetset = null;
Class.forName("com.mysql.jdbc.Driver");
try{
c= DriverManager.getConnection("jdbc:mysql://localhost:3306/wyh?user=root&password=1234");
s = c.createStatement();
boolean b = s.execute("select * fromschool");//执行查询语句,执行的结果是结果集,所以返回值是true
if(b == true){
set= s.getResultSet();
while(set.next()){
System.out.println(set.getString(2));//传入的是表中的索引,从1开始。
}
}
boolean b1 = s.execute("update schoolset score=90 where score=75");//执行更新语句,执行的结果是受影响行数,所以返回值是false
if(b1 == false){
intflag = s.getUpdateCount();
System.out.println(flag);
if(flag>= 1){//做更新操作,受影响行数至少是1
System.out.println("更新成功");
}else{
System.out.println("更新失败");
}
}
}catch (SQLException e) {
//TODO Auto-generated catch block
e.printStackTrace();
}finally{
if(c!=null){//Connection初始值是null,在执行过程中可能会发生异常,如果发生异常了,那么c就没有被赋值,c还是原来的null,这样直接close就会报出空指针异常。所以这里判断一下,如果c不为空,再关闭。
try{
c.close();
s.close();
set.close();
}catch (SQLException e) {
//TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
public class Lianxi3 {
publicstatic void main(String[] args) {
Connectionc = null;
Statements = null;
Scannersc = new Scanner(System.in);
System.out.println("请输入编号");
String id = sc.next();
System.out.println("请输入姓名");
Stringname = sc.next();
System.out.println("请输入课程编号");
Stringcourseid = sc.next();
System.out.println("请输入成绩");
doublescore = sc.nextDouble();
System.out.println("请输入民族");
Stringminzu = sc.next();
try{
Class.forName("com.mysql.jdbc.Driver");
try{
c=DriverManager.getConnection("jdbc:mysql://localhost:3306/wyh?user=root&password=1234");
s= c.createStatement();
Stringsql = "insert into school(id,name,cid,score,minzu)values("+"'"+id+"'"+','+"'"+name+"'"+','+courseid+','+score+","+"'"+minzu+"')";
intflag = s.executeUpdate(sql);
if(flag >=1){
System.out.println("插入成功");
}else{
System.out.println("插入失败");
}
System.out.println("请输入要删除信息的名字");
StringnameDel = sc.next();
Stringsql1 = "delete from school wherename="+"'"+nameDel+"'";
int flag2 = s.executeUpdate(sql1);
if(flag2 >= 1){
System.out.println("删除成功");
}else{
System.out.println("删除失败");
}
}catch (SQLException e) {
//TODO Auto-generated catch block
e.printStackTrace();
}
}catch (ClassNotFoundException e) {
//TODO Auto-generated catch block
e.printStackTrace();
}finally{
try {
if(c!= null)
c.close();
}catch (SQLException e) {
//TODO Auto-generated catch block
e.printStackTrace();
}
try{
if(s!= null)
s.close();
}catch (SQLException e) {
//TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
public class Lianxi4 {
publicstatic void main(String[] args) throws SQLException {
Connectionc = null;
PreparedStatementps = null;
try{
Class.forName("com.mysql.jdbc.Driver");
try{
c= DriverManager.getConnection("jdbc:mysql://localhost:3306/wyh?user=root&password=1234");
String sql = "insert into schoolvalues(?,?,?,?,?)";
ps= c.prepareStatement(sql);
ps.setString(1, "5");
ps.setDouble(4, 93.5);
ps.setString(5, "汉族");
ps.setString(2, "tom");
ps.setString(3, "3");
int flag = ps.executeUpdate();//此处不需要传入SQL语句,与Statement不同,Statement在执行语句时需要传入SQL语句。
if(flag >=1){
System.out.println("添加成功");
}else{
System.out.println("添加失败");
}
}catch (SQLException e) {
//TODO Auto-generated catch block
e.printStackTrace();
}
}catch (ClassNotFoundException e) {
//TODO Auto-generated catch block
e.printStackTrace();
}finally{
if(c!= null){
c.close();
ps.close();
}
}
}
}
public class Lianxi5 {
publicstatic void main(String[] args) throws ParseException, SQLException {
//TODO Auto-generated method stub
Connectionc = null;
PreparedStatementps = null;
try{
Class.forName("com.mysql.jdbc.Driver");
try{
c=DriverManager.getConnection("jdbc:mysql://localhost:3306/wyh?user=root&password=1234");
}catch (SQLException e) {
//TODO Auto-generated catch block
e.printStackTrace();
}
Stringsql = "insert into employee values(?,?,?,?,?,?,?)";
try{
Strings = "2018-10-01";
/*DateFormatdf = new SimpleDateFormat("yyyy年MM月dd日");//创建格式化对象
java.util.Datetime1 = df.parse(s);//将string解析之后,转为Date对象
java.sql.Datetime = new java.sql.Date(time1.getTime());*///time1.getTime()获取util下Date对象的long值,作为参数,创建sql包下Date对象
ps= c.prepareStatement(sql);
ps.setString(1,"wyh");
ps.setInt(2,22);
//ps.setDate(3,time);
ps.setDate(3,java.sql.Date.valueOf(s));
ps.setString(4,"4000");
ps.setString(5,"java程序员");
ps.setInt(6,666);
ps.setString(7,"计算机");
intflag = ps.executeUpdate();
if(flag>= 1){
System.out.println("添加成功");
}else{
System.out.println("添加失败");
}
}catch (SQLException e) {
//TODO Auto-generated catch block
e.printStackTrace();
}
}catch (ClassNotFoundException e) {
//TODO Auto-generated catch block
e.printStackTrace();
}finally{
if(c!= null){
c.close();
ps.close();
}
}
}
}
public class Lianxi6 {
publicstatic void main(String[] args) throws ClassNotFoundException {
ArrayList<Student>list = new ArrayList<Student>();//定义一个ArrayList,盛放查询结果集中的Student对象
Class.forName("com.mysql.jdbc.Driver");
try{
Connectionc = DriverManager.getConnection("jdbc:mysql://localhost:3306/wyh?user=root&password=1234");
Stringsql = "select * from school";
PreparedStatementps = c.prepareStatement(sql);
ResultSetset = ps.executeQuery();
while(set.next()){//遍历结果集,一次一行
Stringid = set.getString(1);//获取表中每一个字段的值
Stringname = set.getString(2);
Stringcid = set.getString(3);
doublescore = set.getDouble(4);
Stringminzu = set.getString(5);
Students = new Student(id,name,cid,score,minzu);//有参构造方法创建Student对象
list.add(s);//将每一行的结果所创建的对象放入ArrayList中
}
}catch (SQLException e) {
//TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(list);//打印list
}
}
public class Student{
@Override
public String toString() {
return"Student [birthday=" + birthday + ", sname=" + sname +", sno="
+ sno + ", className=" +className + "]";
}
private Date birthday;
private String sname;
private int sno;
private String className;
public Student() {
super();
// TODO Auto-generated constructor stub
}
public Student(Date birthday, String sname,int sno, String className) {
super();
this.birthday = birthday;
this.sname = sname;
this.sno = sno;
this.className = className;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
public String getSname() {
return sname;
}
public void setSname(String sname) {
this.sname = sname;
}
public int getSno() {
return sno;
}
public void setSno(int sno) {
this.sno = sno;
}
public String getClassName() {
return className;
}
public void setClassName(String className) {
this.className = className;
}
}