疯狂java


您现在的位置: 疯狂软件 >> 新闻资讯 >> 正文

java简单的数据库查询


 

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

  1.数据库链接类

  1 import java.sql.Connection;

  2 import java.sql.DriverManager;

  3 import java.sql.SQLException;

  4

  5 public class DBHelper {

  6 /**

  7 * 获取数据库链接

  8 *

  9 * @return 数据库链接

  10 */

  11 public static Connection getConnection() {

  12 Connection conn = null;

  13 String driver = "com.microsoft.sqlserver.jdbc.SQLServerDriver";// 驱动

  14 String username = "sa";// 用户名

  15 String password = "sa";// 密码

  16 String url = "jdbc:sqlserver://192.168.1.10;DatabaseName=test";// SqlServer链接地址

  17 try {

  18 Class.forName(driver);//加载驱动类

  19 conn = DriverManager.getConnection(url, username, password);

  20 } catch (ClassNotFoundException e) {

  21 System.out.println("找不到驱动程序类 ,加载驱动失败!");

  22 e.printStackTrace();

  23 } catch (SQLException e) {

  24 System.out.println("数据库连接失败!");

  25 e.printStackTrace();

  26 }

  27 return conn;

  28 }

  29

  30 }

  2.执行查询

  1 import java.sql.Connection;

  2 import java.sql.PreparedStatement;

  3 import java.sql.ResultSet;

  4 import java.sql.SQLException;

  5

  6 public class TestQuery {

  7

  8 public static void main(String[] args) {

  9 Connection conn = DBHelper.getConnection();// 获取数据库链接

  10 PreparedStatement ps = null;

  11 ResultSet rs = null;

  12 try {

  13 String sql = "select * from users";

  14 ps = conn.prepareStatement(sql);

  15 rs = ps.executeQuery();// 执行查询

  16 while (rs.next()) {// 判断是否还有下一个数据

  17 System.out.println("ID:" + rs.getString("id") + " NAME:"

  18 + rs.getString("name"));

  19 }

  20 } catch (SQLException e) {

  21 e.printStackTrace();

  22 } finally {

  23 if (rs != null) {

  24 try {

  25 rs.close();// 关闭记录集

  26 } catch (SQLException e) {

  27 e.printStackTrace();

  28 }

  29 }

  30 if (ps != null) {

  31 try {

  32 ps.close();// 关闭声明

  33 } catch (SQLException e) {

  34 e.printStackTrace();

  35 }

  36 }

  37 if (conn != null) {

  38 try {

  39 conn.close();// 关闭连接

  40 } catch (SQLException e) {

  41 e.printStackTrace();

  42 }

  43 }

  44 }

  45

  46 }

  47

  48 }

  3.执行结果

  ID:00027c20dad4467180be4637d1f6008f NAME:张三

  ID:0c99ddbeba304596ae87f34cfb1e21f7 NAME:李四