JDBC代码实现
import org.junit.Test;
import java.sql.*;
public class JDBC {
@Test
public void test2() throws ClassNotFoundException, SQLException {
Connection conn = null;
Statement stat = null;
ResultSet rs = null;
try {
//1.驱动加载
Class.forName("com.mysql.jdbc.Driver");
//2.获取数据库连接
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb?user=root&password=123456");
//3.获取执行SQL语句的对象
stat = conn.createStatement();
//4.执行SQL语句并获取结果
rs = stat.executeQuery("select * from employee");
//5.处理结果
while (rs.next()) {
System.out.println(rs.getString("name"));
System.out.println(rs.getString(1));
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} finally {
//6.资源关闭
if (rs != null) {
try {
rs.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
} finally {
rs = null;
}
}
if (stat != null) {
try {
stat.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
} finally {
stat = null;
}
}
if (conn != null) {
try {
conn.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
} finally {
conn = null;
}
}
}
}
}
注:
数据库驱动包会自动在类加载时注册驱动,所以不要手动注册数据库驱动,会造成驱动的重复注册:DriverManager.registerDriver(new Driver());
改为使用类加载方式注册:Class.forName(“com.mysql.jdbc.Driver”);