JDBC简单使用
public static void main(String[] args) throws SQLException {
// 1. 注册驱动
Class.forName("com.mysql.jdbc.Driver");
// 2. 获取链接Connection
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/yiyousu","root","mysqlmysql");
// 3. 得到执行SQL语句的对象Satatement
Statement stmt = (Statement) conn.createStatement();
// 4. 执行SQL语句,并返回结果
ResultSet rs = stmt.executeQuery("select * from `user`");
// 5. 处理结果
while (rs.next()) {
System.out.println(rs.getObject(1));
System.out.println(rs.getObject(2));
System.out.println(rs.getObject(3));
System.out.println(rs.getObject(4));
System.out.println(rs.getObject(6));
System.out.println("----------------");
}
// 6. 关闭资源
rs.close();// 关闭结果集
stmt.close();// 关闭读取器
conn.close();// 关闭数据库链接
}
}
// 增删改语句
public static void main(String[] args) throws Exception {
// 1. 注册驱动
Class.forName("com.mysql.jdbc.Driver");
// 2. 获取链接Connection
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/yiyousu", "root", "mysqlmysql");
// 3. 得到执行SQL语句的对象Satatement
Statement stmt = conn.createStatement();
// 4. 执行SQL语句,并返回结果
int i = stmt.executeUpdate("INSERT INTO test (name,age) VALUES('test1',1)");
// 5. 处理结果
System.out.println(i);
// 6. 关闭资源
stmt.close();// 关闭读取器
conn.close();// 关闭数据库链接
}