MySQL - JDBC

来源:互联网 发布:淘宝买到假酒怎么索赔 编辑:程序博客网 时间:2024/05/04 12:24
首先要去官网下载一个叫做MySQLConnector的东西,下载JDBC的版本就行。然后解压以后可以在doc里面找到一个html文件,打开它,里面会有一些实例程序。

在使用之前要先将文件夹里面的jar包导入工程。

其实JDBC本身内容没多少,无非就是一个Connection,一个Statement,一个ResultSet。使用的时候先定义一个Driver,然后将connection连接到某个数据库,输入user和password,接着创建一个statement实例,再接着就是进行具体的数据库操作了。

最后,全部操作完以后,要使用finally关闭掉数据库连接。

Connection conn = null;

Statement stmt = null;

ResultSet rs = null;

try {

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

conn =DriverManager.

getConnection("jdbc:mysql://localhost/mydata?" "user=root&password=heiheijoshua");

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){

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 sqlEx){

sqlEx.printStackTrace();

}

}

其实说实话,真正现在的大多数的数据操作都已经被框架封装好了,比如说JDBC的操作,已经被java的指令,方法,annotation之类的代替了,所以关于MySQL和JDBC的操作,掌握其原理是主要的,其实操作都很简单。


原创粉丝点击