1:首先下载sqljdbc.jar,然后配置ClassPath,然后再在工程文件中把这个(sqljdbc.jar)架包引用上,就可以开始JAVA操作之旅了
打开Eclipse,“文件”→“新建”→“项目”→“Java 项目”,项目名为Test2、
在Eclipse中,选择“窗口”→“首选项...”→“Java”→“已安装的 JRE”,选择已安装的 JRE,点击“编辑”→“添加外部”
选择%ProgramFiles%\sqljdbc_1.1\chs\sqljdbc.jar3、在Test项目的“JRE 系统库”中可以看见sqljdbc.jar,
如果没有可以右键单击项目Test→“构建路径”→“配置构建路径...”→“Java 构建路径”→“库”→“添加外部 JAR...”,
选择%ProgramFiles%\sqljdbc_1.1\chs\sqljdbc.jar4、编写Java代码,如下:
2:下面是JDBC 连接MS SQL的语句
/*
* JDBC常用写法
*/
public static ResultSet GetResultSet(String sql) { String temp1 = ""; ResultSet rs1 = null; try { String driverName = "com.microsoft.sqlserver.jdbc.SQLServerDriver"; String url = "jdbc:sqlserver://localhost:1824; DatabaseName=AATestDB"; String user = "sa"; String password = "123456"; Class.forName(driverName); Connection dbConn = DriverManager .getConnection(url, user, password); try { Statement stmt = dbConn.createStatement(1005, 1008); rs1 = stmt.executeQuery(sql); } catch (SQLException e) { } finally { System.out.println("------------t3----------"); } return rs1; } catch (Exception ex) { System.out.println("------------t4----------"); } return rs1; }
/* * JDBC调用事务 */ public static void GetResultSet(String sql) { try { Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver").newInstance(); String url = "jdbc:sqlserver://localhost:1433; DatabaseName=AATestDB"; String user = "sa"; String password = "123456"; Connection dbConn = DriverManager .getConnection(url, user, password); Statement stmt = dbConn.createStatement(1005, 1008); try { dbConn.setAutoCommit(false); String sql1="select * from ATable where id=1"; String sql2="select * from ATable where id=2"; stmt.executeUpdate(sql1); stmt.executeUpdate(sql2); Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver").newInstance(); dbConn.commit(); } catch (SQLException e) { try { dbConn.rollback(); System.out.println("数据回滚!"); } catch (Exception e2) { e2.printStackTrace(); } } finally { dbConn.setAutoCommit(true); } } catch (Exception ex) { ex.printStackTrace(); } finally{ System.out.println("操作完毕!!"); } }
/*
* JDBC调用事务
*/
public void AAA()
{
String sql="select * from AATable";
ResultSet rs=GetResultSet(sql);
while (rs.next()) {
String aa=rs.getString("AAFiled");
............
}
}