JDBC编程步骤实例
来源:互联网 发布:网络暑假工招聘 编辑:程序博客网 时间:2024/04/30 23:31
JDBC编程步骤:
1、Loader the Driver
1、Class.forName() | Class.forName().newInstance() | new DriverName()
2、实例化时自动向DriverManger注册,不需要显式的调用DriverManger.registerDriver方法
2、Connect to DataBase
1、DriverManger.getConnection()
3、Execute the SQL
1、Connection.CreatStatement()
2、Statement.executeQuery()
3、Statement.executeUpdate()
4、retrieve the result data
1、循环取得结果 while(rs.next())
5、Show the result data
1、将数据库中的各种数据类型转换为java中的类型(getXXX)方法
6、Close
1、close the resultset / close the statement / close the connection
注意:常见的问题
如果自己在面试的时候忘记了某些字符串或者方法的时候这一去注释:
// sorry !我忘了,一时想不起来了,我平时都是用MyEclipes去copy,或者自动生成的如果我去查一下会很快写出来的。
DML语句就是对数据库的插入和修改。只是一点不一样,就是Statement.executeQuery();或者Statement.executeUpdate();
实例:
import java.sql.*;
public class TestMysqlConnection {
/**
* @param args
*/
public static void main(String[] args) {
Connection conn = null; //连接的接口
Statement stmt = null; //声明
ResultSet rs = null; // 结果集
try {
//步骤一(加载驱动)
Class.forName("com.mysql.jdbc.Driver"); //实例化Driver的第一种方法
//new com.mysql.jdbc.Driver //实例化Driver的第一种方法
//步骤二(加载驱动建立连接)
conn = DriverManager
.getConnection("jdbc:mysql://localhost/mydata?user=root&password=root");
//方法一
//getConnection(String url, String user, String password)
// url - jdbc:mysql://localhost:3306/数据库名
//user - 所连接的数据库的用户名 ;password - the user's password
//方法二
//getConnection(String url)
//url - a database url of the form jdbc:subprotocol:subname
//String url = jdbc:mysql://localhost/dataBaseName?user=userName&password=UserPassword;
//步骤三(查询数据)
stmt = conn.createStatement();
rs = stmt.executeQuery("select * from dept");
//步骤四(遍历读取数据)
while (rs.next()) {
//步骤五(显示数据)
System.out.println(rs.getString("deptno"));
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException ex) {
// handle any errors
System.out.println("SQLException: " + ex.getMessage());
System.out.println("SQLState: " + ex.getSQLState());
System.out.println("VendorError: " + ex.getErrorCode());
} finally {
//步骤六(关闭)
try {
if(rs != null) {
rs.close();
rs = null;
}
if(stmt != null) {
stmt.close();
stmt = null;
}
if(conn != null) {
conn.close();
conn = null;
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
- JDBC编程步骤实例
- JAVA JDBC编程步骤
- 【数据库】JDBC编程步骤
- JDBC编程的步骤
- JDBC编程步骤
- JDBC编程步骤
- JDBC编程的步骤
- JDBC编程步骤
- JDBC编程步骤
- JDBC 简单编程步骤
- javaEE jdbc编程步骤
- JDBC编程步骤
- JDBC 编程步骤
- JDBC编程步骤
- JDBC编程的步骤
- JDBC编程步骤
- jdbc编程步骤
- JDBC基本编程步骤
- 中国人的自信从何而来
- 在hibernate中使用P6spy
- 海豚音
- C# 线程同步问题(存档)
- j2me 开发的双色球机选小程序
- JDBC编程步骤实例
- linux——vi编辑器基本使用方法
- SQL Alias
- ORA-16038,ORA-19809,ORA-00312
- eclipse颜色设置以及常用快捷键
- C# 异步调用(存档)
- Servlet笔记
- 唐骏资料
- COM编程入门