连接数据库实现查询员工信息
按步骤操作实现查询
package com.zheng.z;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class JDBC2 {
private Connection conn = null;
private Statement stmt = null;
private ResultSet result = null;
public void queryEMP() {
try {
// 1、加载驱动
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
// 2、建立连接
String url = "jdbc:sqlserver://localhost:1433;databaseName=test";
String username = "zheng";
String pwd = "123";
conn = DriverManager.getConnection(url, username, pwd);
// 3、创建sql语句
stmt = conn.createStatement();
String selectstr = "select * from info";
result = stmt.executeQuery(selectstr);
// 4、处理结果集
System.out.println("员工编号:\t员工姓名:\t工作:");
while (result.next()) {
System.out.println(result.getString("id") + "\t" + result.getString("name") + "\t" + "\t"
+ result.getString("job"));
}
} catch (Exception e) {
e.getStackTrace();
} finally {
// 5、关闭资源
try {
if (result != null) {
result.close();
result = null;
}
if (stmt != null) {
stmt.close();
stmt = null;
}
if (conn != null) {
conn.close();
conn = null;
}
} catch (Exception e) {
e.getStackTrace();
}
}
}
public static void main(String[] args) throws SQLException {
// TODO 自动生成的方法存根
JDBC2 c = new JDBC2();
c.queryEMP();
}
}
实现效果截图