package com.javaee.corejava; import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet; public class JDBCConnect { public JDBCConnect() {
// TODO Auto-generated constructor stub
} public static void main(String[] args) {
try {
//加载mysql的JDBC驱动
Class.forName("com.mysql.jdbc.Driver");
String url="jdbc://localhost:3306/v3x";
String userName="root";
String pwd="123456";
//获取数据库连接
Connection con= DriverManager.getConnection(url, userName, pwd);
String sql="select * from ctp_affair where id=?";
//Statement stmt=con.createStatement();
PreparedStatement pstmt=con.prepareStatement(sql);
pstmt.setLong(1, 0L);
//执行查询
ResultSet rs=pstmt.executeQuery();
while(rs.next()){
String subject=rs.getString("subject");
}
//关闭连接,释放资源
rs.close();// 关闭记录集
pstmt.close();// 关闭声明
con.close();// 关闭连接对象
} catch (Exception e) {
e.printStackTrace();
} } }