package com.mybatis_stu.jdbctest;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.management.RuntimeErrorException;
import org.junit.Test;
public class JdbcTest {
@Test
public void testQuery() {
String url = "jdbc:mysql://127.0.0.1/mybatis_day01";
String name = "com.mysql.jdbc.Driver";
String user = "root";
String password = "Huang123";
Connection connection = null;
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
try {
Class.forName(name);
connection = DriverManager.getConnection(url,user,password);
String sql = "select * from user where username=?";
preparedStatement = connection.prepareStatement(sql);
preparedStatement.setString(1, "王五");
resultSet = preparedStatement.executeQuery();
while (resultSet.next()) {
System.out.println(resultSet.getString("id") + " "
+ resultSet.getString("username"));
}
} catch (Exception e) {
e.printStackTrace();
} finally {
// 释放资源
if (resultSet != null) {
try {
resultSet.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (preparedStatement != null) {
try {
preparedStatement.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (connection != null) {
try {
connection.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
jdbc连接数据库
最新推荐文章于 2023-05-28 10:59:20 发布