java连接SqlServer2008

来源:互联网 发布:dnf改版后光兵技能数据 编辑:程序博客网 时间:2024/05/19 05:39
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 blockSystem.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 blocke.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 blocke.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 blocke.printStackTrace();}return re;}private static void dbclose() {try {st.close();con.close();} catch (SQLException e) {e.printStackTrace();}st = null;con = null;}}
sqljdbc4
0 0
原创粉丝点击