日期:2014-05-16 浏览次数:20494 次
1.连接sql2005的实例
方法1:往数据库中插入数据,创建一个java项目.创建一个class.
建立一个数据库test,创建表名为UserInfo(UserID,password)
使用PrepareStatment
package com.v512.example; import java.sql.*; import java.lang.*; public class JDBCExample { public static void main(String[] args) { String sql = "insert into UserInfo(UserID,password) values(?,?)"; try { Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver"); Connection con = DriverManager.getConnection( "jdbc:sqlserver://localhost:1433;DatabaseName=test", "sa", "123"); PreparedStatement pStatement = con.prepareStatement(sql); pStatement.setString(1, "XXXXX"); pStatement.setString(2, "101010"); pStatement.executeUpdate(); pStatement.close(); con.close(); } catch (Exception e) { // TODO: handle exception } } }
??2.使用statement插入数据
package com.v512.example; import java.sql.*; import java.lang.*; public class JDBCExample { public static void main(String[] args) { ResultSet rs = null; String sql = "insert into UserInfo(UserID,password) values('XXXXXXX','1010010101010')"; try { Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver"); Connection con = DriverManager.getConnection( "jdbc:sqlserver://localhost:1433;DatabaseName=test", "sa", "123"); Statement statement=con.createStatement(); rs=statement.executeQuery(sql); statement.close(); rs.close(); } catch (Exception e) { // TODO: handle exception } } }
?
3.查询数据库的结果!
package com.v512.example; import java.sql.*; import java.lang.*; public class JDBCExample { public static void main(String[] args) { ResultSet rs = null; String sql="select * from UserInfo"; try { Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver"); Connection con = DriverManager.getConnection( "jdbc:sqlserver://localhost:1433;DatabaseName=test", "sa", "123"); PreparedStatement statement=con.prepareStatement(sql); rs=statement.executeQuery(); while (rs.next()) { System.out.println("name:"+rs.getString("UserID")+"\tpassword:"+rs.getString("password")); } statement.close(); con.close(); } catch (Exception e) { } } }
?