1注册驱动(不必要)
DriverManager.registerDriver(new Driver());
2取得连接
Connection con = DriverManager.getConnection(“jdbc:mysql://localhost/stcxxxx?useUnicode=true&characterEncoding=utf-8&useSSL=false”, “root”, “123456”);
3取得statement对象
Statement st = con.createStatement();
4 sql语句
String sql = “select * from student”;
5执行sql语句
ResultSet rs = st.executeQuery(sql);
6遍历结果
while(rs.next())
{
System.out.println(rs.getInt(“Sno”)+" "+rs.getString(“Sname”));
}
7关闭连接一步一步向上关闭
rs,st,con
标准代码
Connection con=null;
Statement st=null;
ResultSet rs=null;
try {
//DriverManager.registerDriver(new Driver());
con = DriverManager.getConnection("jdbc:mysql://localhost/stc_yangzeyu?useUnicode=true&characterEncoding=utf-8&useSSL=false", "root", "123456");
st = con.createStatement();
String sql = "select * from student";
rs = st.executeQuery(sql);
while(rs.next())
{
System.out.println(rs.getInt("Sno")+" "+rs.getString("Sname"));
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
try {
rs.close();
st.close();
con.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
建立连接工具包
public class JdbcUtil {
// public static String driverClass=null;
// public static String url=null;
// public static String user=null;
// public static String password=null;
// static {
// InputStream is =null;
// try {
// Properties properties= new Properties();
// is= JdbcConnect.class.getClassLoader().getResourceAsStream("jdbc.properties");
// properties.load(is);
// driverClass= properties.getProperty(driverClass);
// url=properties.getProperty(url);
// user=properties.getProperty(user);
// password=properties.getProperty(password);
//
// } catch (IOException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
// }
public Connection getCon()
{
Connection conn =null;
InputStream in= null;
try {
in = this.getClass().getResourceAsStream("jdbc.properties");
Properties prop = new Properties();
prop.load(in);
String driver =prop.getProperty("driverClass");
String url = prop.getProperty("url");
String username = prop.getProperty("user");
String password = prop.getProperty("password");
// Class.forName(driver);
conn =DriverManager.getConnection(url, username, password);
} catch (IOException | SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
try {
in.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return conn;
}
}
driverClass=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost/stc_yangzeyu?useUnicode=true&characterEncoding=utf-8&useSSL=false
user=root
password=123456