连接MySQL数据库最简单的代码,不用dbutils、mybatis、c3p0等库的导入。
连接数据库的几个步骤:
1、注册驱动
2、连接数据库
3、创建执行sql语句的执行对象
4、解析执行结果
代码如下:
package com.spectergk.mysql.jdbc;
import Java.sql.DriverManager;
import java.sql.SQLException;
import org.junit.Test;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Connection;
public class TestJdbc {
private final String sqlUrl ="jdbc:mysql://172.20.60.2:3306/spectergk?"
+ "useUnicode=true&characterEncoding=UTF-8";
private final String sqlDriver = "com.mysql.jdbc.Driver";
private final String userName="test";
private final String userPwd="111111";
/*
* 连接数据库
*/
private Connection connection = null;
/*
* 执行sql语句的对象
*/
private PreparedStatement statement = null;
/*
* 执行数据库结果
*/
private ResultSet resultSet = null;
@Test
public void selecteAll() {
String sql_str = "select * from user where uid LIKE ?;";
/*
* jdbc 连接数据库的步骤
* 1、注册驱动
* 2、连接数据库
* 3、获取执行sql语句的对象
* 4、执行sql语句获取结果
*/
try {
/*
* 注册驱动
*/
Class.forName(sqlDriver);
/*
* 连接数据库
*/
connection = (Connection) DriverManager.getConnection(sqlUrl, userName, userPwd);
/*
* 获取执行sql语句的对象
*/
statement = connection.prepareStatement(sql_str);
statement.setString(1, "%liu%");
/*
* 执行sql语句
*/
resultSet = statement.executeQuery();
System.out.println("1111");
while (resultSet.next()) {
//type type = (type) en.nextElement();
System.out.print(resultSet.getString("uid"));
System.out.print(resultSet.getString("realname"));
System.out.println("");
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
try {
if (resultSet != null) {
resultSet.close();
}
if (statement != null) {
resultSet.close();
}
if (connection != null) {
resultSet.close();
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}