您的位置:首页 > 编程语言 > Java开发

JavaWeb之数据库部分--JDBC初步

2016-11-30 00:17 316 查看

一.JDBC概念

JDBC:java database connectivity SUN公司提供的一套操作数据库的标准规范。

JDBC与数据库驱动的关系:接口与实现的关系。

 

JDBC规范(掌握四个核心对象):

DriverManager:用于注册驱动

Connection: 表示与数据库创建的连接

Statement: 操作数据库sql语句的对象

ResultSet: 结果集或一张虚拟表

 

 

二.开发一个JDBC程序

创建java project项目,添加数据库驱动(*.jar)

> JDBC规范在哪里:

 JDK中:

java.sql.*;

javax.sql.*;

> 数据库厂商提供的驱动:jar文件

  *.jar

创建java project项目,添加数据库驱动(*.jar)

新建一个文件夹



然后把jar包拷贝到这个文件夹中,并且添加路径



然后创建一个数据库表,并向表中添加测试数据

1、创建数据库表,并向表中添加测试数据

bogon:~ tinghou$ mysql -u root -p

Enter password: 

Welcome to the MySQL monitor.  Commands end with ; or \g.

Your MySQL connection id is 1872

Server version: 5.6.12 MySQL Community Server (GPL)

Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved.

Oracle is a registered trademark of Oracle Corporation and/or its

affiliates. Other names may be trademarks of their respective

owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql> use day06;

Reading table information for completion of table and column names

You can turn off this feature to get a quicker startup with -A

Database changed

mysql> desc users;

+----------+-------------+------+-----+---------+----------------+

| Field    | Type        | Null | Key | Default | Extra          |

+----------+-------------+------+-----+---------+----------------+

| id       | int(11)     | NO   | PRI | NULL    | auto_increment |

| name     | varchar(40) | YES  |     | NULL    |                |

| password | varchar(40) | YES  |     | NULL    |                |

| email    | varchar(60) | YES  |     | NULL    |                |

| birthday | date        | YES  |     | NULL    |                |

+----------+-------------+------+-----+---------+----------------+

5 rows in set (0.01 sec)

mysql> select *from users;

+----+------+----------+-------------+------------+

| id | name | password | email       | birthday   |

+----+------+----------+-------------+------------+

|  1 | zs   | 123456   | zs@sina.com | 1980-12-04 |

|  2 | ls   | 123      | ls@sina.com | 1990-01-01 |

+----+------+----------+-------------+------------+

2 rows in set (0.01 sec)

mysql> 

三、JDBC常用的类和接口详解

1、java.sql.Drivermanager类 : 创建连接

a、注册驱动

DriverManager.registerDriver(new com.mysql.jdbc.Driver());不建议使用

原因有2个:

> 导致驱动被注册2次。

> 强烈依赖数据库的驱动jar

解决办法:

Class.forName("com.mysql.jdbc.Driver");

b、与数据库建立连接

static Connection getConnection(String url, Stringuser, String password)

          试图建立到给定数据库 URL的连接。

getConnection("jdbc:mysql://localhost:3306/day06","root", "root");

URL:SUN公司与数据库厂商之间的一种协议。

jdbc:mysql://localhost:3306/day06

协议 子协议  IP :端口号 数据库

mysql: jdbc:mysql://localhost:3306/day14 或者 jdbc:mysql:///day14(默认本机连接)

oracle: jdbc:oracle:thin:@localhost:1521:sid 

                      Propertiesinfo = new Properties();//要参考数据库文档

                      info.setProperty("user","root");

                      info.setProperty("password","root");

getConnection(String url, Properties info)

getConnection(String url)

DriverManager.getConnection("jdbc:mysql://localhost:3306/day14?user=root&password=root");

2、java.sql.Connection接口:一个连接

接口的实现在数据库驱动中。所有与数据库交互都是基于连接对象的。

Statement createStatement(); //创建操作sql语句的对象

3、java.sql.Statement接口: 操作sql语句,并返回相应结果的对象(小货车)

接口的实现在数据库驱动中。用于执行静态SQL 语句并返回它所生成结果的对象。

ResultSet  executeQuery(String sql) 根据查询语句返回结果集。只能执行select语句。

 int executeUpdate(String sql) 根据执行的DML(insertupdate delete)语句,返回受影响的行数。

booleanexecute(String sql)  此方法可以执行任意sql语句。返回boolean值,表示是否返回ResultSet结果集。仅当执行select语句,且有返回结果时返回true, 其它语句都返回false;

4、java.sql.ResultSet接口: 结果集(客户端存表数据的对象)

a、封装结果集的。

提供一个游标,默认游标指向结果集第一行之前。

调用一次next(),游标向下移动一行。

提供一些get方法。

封装数据的方法

ObjectgetObject(int columnIndex); 根据序号取值,索引从1开始

ObjectgetObject(String ColomnName); 根据列名取值。

 

将结果集中的数据封装到javaBean中

java的数据类型与数据库中的类型的关系

byte          tityint

short         smallint

int           int

long          bigint

float         float

double        double

String        char archer

 Date         date

 

boolean next()     将光标从当前位置向下移动一行

int getInt(int colIndex) 以int形式获取ResultSet结果集当前行指定列号值

int getInt(String colLabel)      以int形式获取ResultSet结果集当前行指定列名值

float getFloat(int colIndex)    以float形式获取ResultSet结果集当前行指定列号值

float getFloat(String colLabel)         以float形式获取ResultSet结果集当前行指定列名值

String getString(int colIndex)          以String 形式获取ResultSet结果集当前行指定列号值

String getString(String colLabel)    以String形式获取ResultSet结果集当前行指定列名值

Date getDate(int columnIndex); 

Date getDate(String columnName);

void close()          关闭ResultSet 对象

 

b、可移动游标的方法

 boolean next() 将光标从当前位置向前移一行。

            boolean previous()

             将光标移动到此 ResultSet 对象的上一行。

 boolean absolute(int row) 参数是当前行的索引,从1开始

                 根据行的索引定位移动的指定索引行。

 void afterLast()

          将光标移动到末尾,正好位于最后一行之后。

 void beforeFirst()

          将光标移动到开头,正好位于第一行之前。

 

c、释放资源

资源有限,要正确关闭。

和数据库建立连接有以下3种方式,详见代码

package com.tinghou.jdbcdemo;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

import org.junit.Test;

//使用JDBC技术实现查询数据库数据,并显示在控制台中
public class Demo1 {
@Test
public void test1() throws Exception  {

//加载驱动
Class.forName("com.mysql.jdbc.Driver");
//获取连接Connection
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/day06", "root", "123456");
//得到执行sql语句的对象Statement
Statement stmt = conn.createStatement();
//执行sql语句,并返回结果
ResultSet rs = stmt.executeQuery("select id,name,password,email,birthday from users");
//处理结果
while(rs.next()){
System.out.println(rs.getObject(1));
System.out.println(rs.getObject(2));
System.out.println(rs.getObject(3));
System.out.println(rs.getObject(4));
System.out.println(rs.getObject(5));
System.out.println("-----------------");
}
//关闭资源
rs.close();
stmt.close();
conn.close();
}

@Test
public void test2() throws Exception{
//加载驱动
Class.forName("com.mysql.jdbc.Driver");
//获取连接Connection
Properties info = new Properties();
info.setProperty("user", "root");
info.setProperty("password", "123456");

Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/day06", info);
//得到执行sql语句的对象Statement
Statement stmt = conn.createStatement();
//执行sql语句,并返回结果
ResultSet rs = stmt.executeQuery("select id,name,password,email,birthday from users");
//处理结果
while(rs.next()){
System.out.println(rs.getObject(1));
System.out.println(rs.getObject(2));
System.out.println(rs.getObject(3));
System.out.println(rs.getObject(4));
System.out.println(rs.getObject(5));
System.out.println("-----------------");
}
//关闭资源
rs.close();
stmt.close();
conn.close();
}

@Test
public void test3() throws Exception{
//加载驱动
Class.forName("com.mysql.jdbc.Driver");
//获取连接Connection
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/day06?user=root&password=123456");
//得到执行sql语句的对象Statement
Statement stmt = conn.createStatement();
//执行sql语句,并返回结果
ResultSet rs = stmt.executeQuery("select id,name,password,email,birthday from users");
//处理结果
while(rs.next()){
System.out.println(rs.getObject(1));
System.out.println(rs.getObject(2));
System.out.println(rs.getObject(3));
System.out.println(rs.getObject(4));
System.out.println(rs.getObject(5));
System.out.println("-----------------");
}
//关闭资源
rs.close();
stmt.close();
conn.close();
}

@Test
public void test4() throws Exception{
//获取连接Connection
Connection conn = null;
//得到执行sql语句的对象Statement
Statement stmt = null;
//执行sql语句,并返回结果
ResultSet rs = null;
try {
//加载驱动
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/day06?user=root&password=123456");
stmt = conn.createStatement();
rs = stmt.executeQuery("select id,name,password,email,birthday form users");
//处理结果
while(rs.next()){
System.out.println(rs.getObject(1));
System.out.println(rs.getObject(2));
System.out.println(rs.getObject(3));
System.out.println(rs.getObject(4));
System.out.println(rs.getObject(5));
System.out.println("-----------------");
}
} catch (Exception e) {
e.printStackTrace();
}finally{
//关闭资源
if(rs!=null){
try {
rs.close();
} catch (Exception e) {
e.printStackTrace();
}
rs = null;
}
if(stmt!=null){
try {
stmt.close();
} catch (Exception e) {
e.printStackTrace();
}
stmt = null;
}
if(conn!=null){
try {
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
conn = null;
}

}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐