最基本的连接sqlserver数据库的步骤

1.加载sqlserver的驱动程序

2.获得数据库的连接

3.准备preparedStatement预处理对象

4.设置查询的sql语句中参数

5.查询返回结果集

6.遍历结果集

7.关闭连接

import java.sql.*;

public class JdbcTest {
    public static void main(String[] args) {
         Connection connection=null;//数据库连接
         PreparedStatement preparedStatement=null;//sql的预处理对象
         ResultSet resultSet=null;//查询返回的结果集

        try {
            Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");//1
            connection= DriverManager.getConnection("jdbc:sqlserver://localhost:1433;Database=Mybatis","sa","123456");//2

            String sql="select * from t_user where id=?";
            preparedStatement=connection.prepareStatement(sql);//3
            preparedStatement.setInt(1,4);//4
            resultSet=preparedStatement.executeQuery();//5
            while(resultSet.next()){//6
                System.out.println(resultSet.getString(1));
                System.out.println(resultSet.getString(2));
                System.out.println(resultSet.getString(3));
                System.out.println(resultSet.getString(4));
                System.out.println(resultSet.getString(5));
            }
            if(connection!=null){//7
                connection.close();
            }

            if(preparedStatement!=null){
                preparedStatement.close();
            }

            if(resultSet!=null){
                resultSet.close();
            }
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }


    }
}
经验分享 程序员 微信小程序 职场和发展