Java数据库的操作
如何通过JDBC访问数据库
Java数据库连接用于在Java程序中实现数据库操作功能,它提供了执行SQL语句,访问各种数据库的方法,并为各种不同的数据库提供统一的操作接口,**java.sql包中包括了JDBC操作数据的所有的类。**具体操作步骤如下:
**(1)加载JDBC驱动器。**将数据库的JDBC驱动加载到classpath中,在基于JavaEE的Web应用开发中,通常要把目标数据库产品的JDBC驱动复制到WEB-INF/lib下
**(2)加载JDBC驱动,**并将其注册到DriverManager中。一般使用反射Class.forName(String driverName)
(3)建立数据库的连接,取得Connection对象。一般通过DriverManager.getConnection(url,username,passwd)方法实现,其中,url:连接数据库的字符串,username:连接数据库的用户 ,passwd:连接数据的密码
(4)建立Statement对象或者是PreparedStatement对象。
(5)执行SQL语句
(6)访问结果集ResultSet对象
**(7)依次将ResultSet,Statement,PreparedStatement,Connection对象关闭,**释放掉所占用的资源(因为JDBC驱动底层通常都是通过网络IO实现SQL命令与数据传输)
使用JDBC访问MySQL的例子
package com.hfh;
import java.sql.*;
public class Demo{
public static void main(String[] args ) throws Exception{
String user = "root";
String password = "root";
String url = "jdbc:mysql://localhost/hfh_db?useUnicode=true&characterEncoding=UTF-8";
String driver = "com.mysql.jdbc.Driver";
Connection con = null;
Statement stmt = null;
ResultSet rs = null;
try {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection(url,user,password);
stmt = con.createStatement();
stmt.execute("insert into Employee (name,age) value('James',20)");
stmt.execute("insert into Employee (name,age) value('Bob',25)");
rs = stmt.executeQuery("select * from Employee");
while (rs.next()) {
System.out.println(rs.getInt(1) + " " + rs.getString(2)+ " " +rs.getInt(3));
}
} catch (SQLException e1) {
e1.printStackTrace();
}finally {
try {
if (rs != null) rs.close();
if(stmt != null) stmt.close();
if (con != null) con.close();
} catch (SQLException e) {
System.out.println(e.getMessage());
}
}
}
}
![Alt]
数据库名字最好不要取db…创建完表后,然后对表设计,把自动递增勾上