写在前面
- 获得与数据库的连接对象Connection
- 通过连接对象获取Statement对象connection.creatStatement()
- sql语句字符串
- 执行sql语句
非查询sql语句statement.executeUpdate()
查询sql语句statement.executeQuery()
- 执行查询语句返回一个结果集对像ResultSet
- 关闭connection、statement和resultSet
详细过程
//获取连接对象
Class.forName("com.mysql.jdbc.Driver");
Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/数据库名", "用户名", "密码");
//通过连接对象获取Statement对象
Statement statement = connection.createStatement();
//创建sql语句的字符串
String SQLString = "create table person(id int, name varchar(10))";
//执行查询语句
//执行非查询的sql语句(executeUpdate)
//返回值表示影响的行数
statement.extcuteUpdate(sqlString);
//关闭数据库连接
connection.close();
statement.close();
Connection connection = JdbcUtil.getConnection();
Statement statement = connection.createStatement();
String sqlString = "select * from 表名";
//executeQuery执行查询的sql语句
//返回一个结果集
ResultSet resultSet = statement.executeQuery(sqlString);
//是否有下一个元素
while(resultSet.next()) {
//索引从1开始
//根据列的值类型选择相应的方法
resultSet.getInt(第几列);
resultSet.getString("列名");
}
JdbcUtil.closeAll(connection, statement, resultSet);