public Connection conn;
public Connection getConn() {
try {
//所使用的驱动类
Class.forName("com.mysql.jdbc.Driver");
//创建连接
conn = DriverManager
.getConnection(
"jdbc:mysql://localhost/mysql?useUnicode=true&characterEncoding=GBK",
"root", "root");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return conn;
}
jdbc:mysql://localhost/mysql?useUnicode=true&characterEncoding=GBK
jdbc:mysql://
固定格式
localhost
连接地址,不用加端口,不过默认的是3306
mysql
所用的数据库名称
useUnicode=true&characterEncoding=GBK
连接属性,根据数据库编码修改GBK->UTF-8
//创建数据库执行容器
Statement stmt = conn.createStatement();
//创建查询数据集
ResultSet rs = stmt.executeQuery("select * from user");
//循环数据库,
while (rs.next()) {
System.out.print(rs.getString(1));
System.out.print(rs.getString("user"));
System.out.println(rs.getString("password"));
}
//完成查询之后必须关闭所有数据库操作对象
rs.close();
stmt.close();
conn.close();