步骤如下:
1.加载驱动
2.获取链接
3.得到执行sql的语句对象,statement或者prepareStatement,使用PreparedStatement注入的方式保证安全性。
4.执行sql查询语句,并返回结果
5关闭资源
本次使用的sqlServer和Student的数据库
代码如下:
import java.sql.*;
public class Jdbc1 {
//驱动的链接
static private String comDriver="com.microsoft.sqlserver.jdbc.SQLServerDriver";
//使用的数据库jdbc:sqlserver://localhost:1433; DatabaseName=student
//localhost本地地址,1433是sqlserver的端口号,mysql的端口号为3306默认,student是数据库名
static private String url="jdbc:sqlserver://localhost:1433;DatabaseName=student";
//登入数据库的用户名
static private String user="sa";
static private String password="123";
static private String sql="select *from stu";
static private ResultSet rs;
static private Statement stmt;
static private Connection conn;
public Jdbc1(){
}
public static void main(String[] args) {
try {
//加载驱动的方式 1;
// try {
// DriverManager.registerDriver(new com.microsoft.sqlserver.jdbc.SQLServerDriver());
// } catch (Exception e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
//加载驱动的方式 2;
Class.forName(comDriver);
//连接数据库
conn= DriverManager.getConnection(url, user, password);
//得到执行sql语句的对象Statement,一般使用prepareStatement注入的方式
stmt=conn.createStatement();
//执行sql并返回结果
rs=stmt.executeQuery(sql);
while(rs.next()){
System.out.println("输出:"+rs.getObject(1)+" ");
System.out.println("输出:"+rs.getObject(2)+" ");
System.out.println("输出:"+rs.getObject(3)+" ");
System.out.println("---------------");
}
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}finally{
try {
if(rs!=null){
rs.close();
}
if(stmt!=null){
stmt.close();
}
if(conn!=null){
conn.close();
}
}
catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
运行结果图:
![运行图](https://img-blog.csdnimg.cn/20200311163119361.jpg?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L1NTUV9RU1M=,size_16,color_FFFFFF,t_70)