使用 jdbc 从数据库中查询数据

来源:互联网 发布:清穿记事 作者 知华年 编辑:程序博客网 时间:2024/06/05 09:45
package jdbcTest;import java.sql.Connection;import java.sql.DriverManager;import java.sql.PreparedStatement;import java.sql.ResultSet;import java.sql.SQLException;public class JdbcTest {public static void main(String[]args){//数据库链接Connection Connection = null;//预编译的Statement,通过Statement 操作数据库PreparedStatement ps = null;//结果集ResultSet R = null;try {//加载数据库驱动Class.forName("com.mysql.jdbc.Driver");//通过驱动管理类,获取数据库链接try {Connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/spring","root","root");//定义sql 语句String sql = "select * from user where name=?";//获取预处理statementps = Connection.prepareStatement(sql);//设置参数,第一个参数为 sql 语句中参数的序号,第二个参数为设置的参数值ps.setString(1, "mx");//向数据库发出 sql 查询,返回查询结果集R = ps.executeQuery();while(R.next()){System.out.println(R.getString("id")+"  "+R.getString("name")+"   "+R.getString("password"));}} catch (SQLException e) {// TODO Auto-generated catch blocke.printStackTrace();}finally{//释放资源if(R!=null){try {R.close();} catch (SQLException e) {// TODO Auto-generated catch blocke.printStackTrace();}}if(ps!=null){try {ps.close();} catch (SQLException e) {// TODO Auto-generated catch blocke.printStackTrace();}}if(Connection!=null){try {Connection.close();} catch (SQLException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}} catch (ClassNotFoundException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}