Java Web 4.2 JDBC访问数据库

来源:互联网 发布:mac如何打拼音声调 编辑:程序博客网 时间:2024/06/05 05:10

使用JDBC访问数据库,首先需要加载数据库的驱动程序,然后利用连接符号串实现连接,创建连接对象,再创建执行SQL的执行语句并实现数据库的操作。

访问流程:

(1)注册驱动

(2)建立连接(Connection)

(3)创建数据库操作对象用于执行SQL的语句

(4)执行语句

(5)处理执行结果

(6)释放资源


4.2.1注册驱动MySql的驱动程序

1.将驱动程序文件添加到应用项目

2.加载注册指定的数据库驱动程序

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


4.2.2JDBC连接数据库创建连接对象

1.数据库连接的URL

如下:

String url1="jdbc:mysql:

String url2="?user=root&password=密码";

String url3="&useUnicode=true&characterEncoding=UTF-8";

String url=url1+url2+url3;

*由于串较长,分为3个子串,然后连接形成连接串url

2.利用连接符号字实现连接,获取连接对象

①static Connection getConnection(String url)

②static Connection getConnection(String url,Properties info);

③static Connection getConnection(String url,String user,String password);

*实际操作中,一般采用第一种格式

3.利用JDBC连接MySQL数据库,获取连接对象的通用格式

String driverName="com.mysql.jdbc.Driver";

String userName="root";

String userPwd="123456";

String dbName="students";

String url1="jdbc:mysql://localhost:3306/"+dbName;

String url2="?user="+userName+"&password="+userPwd;

String url3="&useUnicode=true&characterEncoding=UTF-8";

String url=url1+url2+url3;

Class.forName(driverName);

Connection conn=DriverManager.getConnection(url);


4.2.3 创建数据库的操作对象

1.创建Statement对象

例如:Statement stmt = conn.createStatement();

*createStatement()方法是无参方法

2.创建PreparedStatement对象

(1)PreparedStatement对象使用PreparedStatement()方法创建,并在创建时直接指定SQL语句。

String sql="......";

PreparedStatement pstmt = conn.preparedStatement(sql);

(2)使用带参数的SQL语句(“?”表示参数值),创建PreparedStatement对象。

例如:String ss="select *from stu_info where age>=? and sex=?";

    PreparedStatement pstmt = conn.preparedStatement(ss);