public class JdbcConnect {
public static void main(String[] args) {
User user = new User();
PreparedStatement preparedStatement = null; ResultSet resultSet = null; Connection connection = null;
try { Class.forName("com.mysql.jdbc.Driver"); connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/mybatis?characterEncoding=utf-8&useSSL=false", "root", "root"); String sql = "select * from user where username = ?"; preparedStatement = connection.prepareStatement(sql); preparedStatement.setString(1, "测试"); resultSet = preparedStatement.executeQuery(); while (resultSet.next()) { int id = resultSet.getInt("id"); String username = resultSet.getString("username"); user.setId(id); user.setUserName(username); } System.out.println(user); } catch (Exception e) { e.printStackTrace(); } finally { if (null != resultSet) { try { resultSet.close(); } catch (SQLException e) { e.printStackTrace(); } } if (preparedStatement != null) { try { preparedStatement.close(); } catch (SQLException e) { e.printStackTrace(); } } if (connection != null) { try { connection.close(); } catch (SQLException e) { e.printStackTrace(); }
} }
} }
|