Java读取SQL server数据库
要打开SQL server 的三个服务,然后再执行代码。
package com.sql; import java.sql.SQLException; import java.sql.Statement; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; public class demo { public static void main(String[] args) { String user = "sa"; String password = "root"; Connection conn; Statement stmt; ResultSet rs; // String url = "jdbc:sqlserver://127.0.0.1:1433;DatabaseName=student_db;"; String url = "jdbc:sqlserver:DESKTOP-I8G440K/SQLEXPRESS:1433;DatabaseName=master"; String sql = "select * from dbo.MSreplication_options"; try { // 连接数据库 conn = DriverManager.getConnection(url, user, password); // 建立Statement对象 stmt = conn.createStatement(); // 执行数据库查询语句 // rs = stmt.executeQuery(sql); // while (rs.next()) { // String id = rs.getString("s_id"); // String name = rs.getString("S_name"); // float score = rs.getFloat("s_score"); // String sex = rs.getString("s_sex"); // System.out.println("学号 "+id+"姓名 "+name+"成绩 "+score+"性别 "+sex); // } // if (rs != null) { // rs.close(); // rs = null; // } // if (stmt != null) { // stmt.close(); // stmt = null; // } // if (conn != null) { // conn.close(); // conn = null; // } } catch (SQLException e) { e.printStackTrace(); System.out.println("数据库连接失败"); } } }