系统环境
- Java版本:Java8
- 开发环境:eclipse
- 所需jar包:mysql-connector-java-5.1.7-bin.jar
- MySQL版本:MySQL5.7
- windows版本:win10
示例代码
package com.jdbc;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class JDBCDemo1 {
public static void demo1() {
Connection connection = null;
Statement statement = null;
ResultSet resultSet = null;
try {
// 1.加载驱动
//DriverManager.registerDriver(new Driver()); // 会注册两次
Class.forName("com.mysql.jdbc.Driver");
// 2.获得连接
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/jdbctest", "root", "sky06xky");
// 3.创建执行SQL的对象,并且执行其语句
// 3.1创建执行SQL的对象
String sqlString = "select * from user";
statement = connection.createStatement();
// 3.2执行sql语句
resultSet = statement.executeQuery(sqlString);
while (resultSet.next()) {
int uid = resultSet.getInt("uid");
String usernameString = resultSet.getString("username");
String passwordString = resultSet.getString("password");
String nameString = resultSet.getString("name");
System.out.println(uid+" "+usernameString+" "+passwordString+" "+nameString+ " ");
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
// 4,释放资源
if (resultSet != null) {
try {
resultSet.close();
} catch (SQLException e) {
e.printStackTrace();
}
resultSet = null;
}
if (statement != null) {
try {
statement.close();
} catch (SQLException e) {
e.printStackTrace();
}
statement = null;
}
if (connection != null) {
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
public static void main(String[] args) {
demo1();
}
}
大致开发步骤
- 注册MySQL数据库驱动,并加载其驱动
- 获得一个数据库连接
- 创建执行SQL的对象,并编写其SQL语句
- 释放所用到的资源
其中第四步是及其重要的,因为要及时的释放,才能让其服务器的资源不至于那么的紧张。
释放资源的关键代码
if (resultSet != null) {
try {
resultSet.close();
} catch (SQLException e) {
e.printStackTrace();
}
resultSet = null;
}
if (statement != null) {
try {
statement.close();
} catch (SQLException e) {
e.printStackTrace();
}
statement = null;
}
if (connection != null) {
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}