package org.apache.hadoop.examples;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
public class Sqlhelper {
private static Connection con = null;
private static Statement st = null;
private static ResultSet rs = null;
private static String user = "sa";
private static String url = "jdbc:sqlserver://192.168.2.210:1433;databaseName=LogBase";
private static String password = "Sa123456";
// 得到链接
public static Connection getConnection() throws ClassNotFoundException {
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
con = DriverManager.getConnection(url, user, password);
} catch (SQLException e) {
// TODO Auto-generated catch block
System.out.print("error:connect the sqlserver!!");
con = null;
e.printStackTrace();
}
return con;
}
private static ResultSet search(String sql, Connection con)
throws SQLException {
if (con == null) {
try {
con=getConnection();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (st == null) {
st = con.createStatement();
}
ResultSet rs = st.executeQuery(sql);
return rs;
}
public static ArrayList<String[]> GetData() throws ClassNotFoundException
{
ArrayList<String[]> re=new ArrayList<String[]>();
String sp="select a.PID as ppid,a.ProductID as pid,a.[Level],a.BrandAttr from ProductInfo a,ProductInfo b where a.PID=B.ProductID order by a.[Level]";
try {
rs=search(sp,con);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
int col=rs.getMetaData().getColumnCount();
while(rs.next()){
String ppid = rs.getString("ppid");
String pid = rs.getString("pid");
System.out.println("ppid:"+ppid+" pid:"+pid);
}
dbclose();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return re;
}
private static void dbclose() {
try {
st.close();
con.close();
} catch (SQLException e) {
e.printStackTrace();
}
st = null;
con = null;
}
}
sqljdbc4
java连接SqlServer2008
最新推荐文章于 2024-07-27 03:51:43 发布