java简单的数据库查询(SQLServer数据库)

时间:2022-12-13 23:03:12

1.数据库链接类

 import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException; public class DBHelper {
/**
* 获取数据库链接
*
* @return 数据库链接
*/
public static Connection getConnection() {
Connection conn = null;
String driver = "com.microsoft.sqlserver.jdbc.SQLServerDriver";// 驱动
String username = "sa";// 用户名
String password = "sa";// 密码
String url = "jdbc:sqlserver://192.168.1.10;DatabaseName=test";// SqlServer链接地址
try {
Class.forName(driver);//加载驱动类
conn = DriverManager.getConnection(url, username, password);
} catch (ClassNotFoundException e) {
System.out.println("找不到驱动程序类 ,加载驱动失败!");
e.printStackTrace();
} catch (SQLException e) {
System.out.println("数据库连接失败!");
e.printStackTrace();
}
return conn;
} }

2.执行查询

 import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException; public class TestQuery { public static void main(String[] args) {
Connection conn = DBHelper.getConnection();// 获取数据库链接
PreparedStatement ps = null;
ResultSet rs = null;
try {
String sql = "select * from users";
ps = conn.prepareStatement(sql);
rs = ps.executeQuery();// 执行查询
while (rs.next()) {// 判断是否还有下一个数据
System.out.println("ID:" + rs.getString("id") + "\tNAME:"
+ rs.getString("name"));
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
if (rs != null) {
try {
rs.close();// 关闭记录集
} catch (SQLException e) {
e.printStackTrace();
}
}
if (ps != null) {
try {
ps.close();// 关闭声明
} catch (SQLException e) {
e.printStackTrace();
}
}
if (conn != null) {
try {
conn.close();// 关闭连接
} catch (SQLException e) {
e.printStackTrace();
}
}
} } }

3.执行结果

ID:00027c20dad4467180be4637d1f6008f    NAME:张三
ID:0c99ddbeba304596ae87f34cfb1e21f7 NAME:李四