Java访问数据库的具体步骤:


1.加载(注册)数据库
驱动加载就是把各个数据库提供的访问数据库的API加载到我们程序进来,加载JDBC驱动,并将其注册到DriverManager中,每一种数据库提供的数据库驱动不一样,加载驱动时要把jar包添加到lib文件夹下,下面看一下一些主流数据库的JDBC驱动加裁注册的代码:
//Oracle8/8i/9iO数据库(thin模式)
Class.forName("oracle.jdbc.driver.OracleDriver").newInstance();
//Sql Server7.0/2000数据库
Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver");
//Sql Server2005/2008数据库
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
//DB2数据库
Class.froName("com.ibm.db2.jdbc.app.DB2Driver").newInstance();
//MySQL数据库
Class.forName("com.mysql.jdbc.Driver").newInstance();
2.建立链接
建立数据库之间的连接是访问数据库的必要条件,就像南水北调调水一样,要想调水首先由把沟通的河流打通。建立连接对于不同数据库也是不一样的,下面看一下一些主流数据库建立数据库连接,取得Connection对象的不同方式:
//Oracle8/8i/9i数据库(thin模式)
String url="jdbc:oracle:thin:@localhost:1521:orcl";
String user="scott";
String password="tiger";
Connection conn=DriverManager.getConnection(url,user,password);
//Sql Server7.0/2000/2005/2008数据库
String url="jdbc:microsoft:sqlserver://localhost:1433;DatabaseName=pubs";
String user="sa";
String password="";
Connection conn=DriverManager.getConnection(url,user,password);
//DB2数据库
String url="jdbc:db2://localhost:5000/sample";
String user="amdin"
String password=-"";
Connection conn=DriverManager.getConnection(url,user,password);
//MySQL数据库
String url="jdbc:mysql://localhost:3306/testDB?user=root&password=root&useUnicode=true&characterEncoding=gb2312";
Connection conn=DriverManager.getConnection(url);
3. 执行SQL语句
数据库连接建立好之后,接下来就是一些准备工作和执行sql语句了,准备工作要做的就是建立Statement对象PreparedStatement对象,例如:
//建立Statement对象
Statement stmt=conn.createStatement();
//建立PreparedStatement对象
String sql="select * from user where userName=? and password=?";
PreparedStatement pstmt=Conn.prepareStatement(sql);
pstmt.setString(1,"admin");
pstmt.setString(2,"liubin");
做好准备工作之后就可以执行sql语句了,执行sql语句:
String sql="select * from users";
ResultSet rs=stmt.executeQuery(sql);
//执行动态SQL查询
ResultSet rs=pstmt.executeQuery();
//执行insert update delete等语句,先定义sql
stmt.executeUpdate(sql);
4.处理结果集
访问结果记录集ResultSet对象。例如:
while(rs.next)
{
out.println("你的第一个字段内容为:"+rs.getString("Name"));
out.println("你的第二个字段内容为:"+rs.getString(2));
}
5.关闭数据库
依次将ResultSet、Statement、PreparedStatement、Connection对象关 闭,释放所占用的资源.例如:
rs.close();
stmt.clost();
pstmt.close();
con.close();

猜你喜欢

转载自blog.csdn.net/weixin_41648325/article/details/80623815