import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
/**
* 数据库连接类
* @author Administrator
*
*/
public class Connection {
/**
* 需要的链接字符串
*/
private static final String str1 = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
private static final String url = "jdbc:sqlserver://localhost:1433;DatabaseName=NorthWind" ;
private static final String user = "sa";
private static final String password= "910627";
java.sql.Connection conn ;
Statement st;
ResultSet rs;
/*
* 加载数据驱动
*/
static {
try {
Class.forName(str1);
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/*
* 链接方法
*/
private java.sql.Connection getConnection(){
try {
conn = DriverManager.getConnection(url,user,password);
} catch (Exception e) {
// TODO: handle exception
}
return conn;
}
/**
* 查询方法
* @param sql
* @return
*/
public ResultSet getData(String sql){
try {
conn = this.getConnection();
st = conn.createStatement();
rs = st.executeQuery(sql);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return rs;
}
/*
* 更新方法
*/
public int updata(String sql){
int line = 0;
try {
line = st.executeUpdate(sql);
if(line>0){
System.out.println( line +"行受影响");
}
} catch (SQLException e) {
System.out.println("更新失败");
e.printStackTrace();
}
return line;
}
/**
* 关闭链接
*/
public void close(){
try {
rs.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
st.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
conn.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
------------------------------------------------------------------------------------------------------------------------------
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Scanner;
import com.iflytek.zhang.Connection;
/**
* 测试NorthWInd类
* @author Administrator
*
*/
public class NorthWind {
public static void main(String[] args) {
System.out.println("输入订单号");
//接收订单号
Scanner sc = new Scanner(System.in);
String orderid = sc.next();
String str = "select ShipName,OrderDate,CompanyName from Orders,Shippers where ShipVia = ShipperID and OrderID ='" + orderid + "'" ;
Connection conn = new Connection();
try {
ResultSet rs = conn.getData(str);
while(rs.next()){
System.out.println("姓名: "+rs.getString(1));
System.out.println("订购日期: "+rs.getString(2));
System.out.println("物流:"+rs.getString(3));
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
------------------------------------------------------------------------------------------------------------------------
运行结果
输入订单号
10255
姓名: 方先生
订购日期: 1996-07-12 00:00:00.0
物流:联邦货运