java与sqlserver 2008_java连接SqlServer2008

本文介绍了一个名为Sqlhelper的Java类的实现,该类用于连接SQL Server数据库并执行基本的数据检索操作。具体包括数据库连接的建立、SQL语句的执行及结果集的处理等。通过示例展示了如何使用此类进行产品信息的查询。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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 GetData() throws ClassNotFoundException

{

ArrayList re=new ArrayList();

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值