日期:2014-05-16 浏览次数:20436 次
import java.sql.*; public class ConnDatabase { private static final String DBDRIVER="com.microsoft.sqlserver.jdbc.SQLServerDriver"; private static final String DBURL="jdbc:sqlserver://localhost:1433;DatabaseName=School1"; private static final String DBUSER="sa"; private static final String DBPWD="sa"; //Refresh public static void Query(ResultSet rs) throws Exception{ System.out.println("No\tName\tAge\tSex");//学号、姓名、年龄、性别 while(rs.next()){ String no = rs.getString("No"); String name = rs.getString("Name"); int age = rs.getInt("Age"); String sex = rs.getString("Sex"); System.out.println(no+"\t"+name+"\t"+age+"\t"+sex); } } public static void main(String[] args) throws Exception{ Class.forName(DBDRIVER);//加载驱动 Connection conn = DriverManager.getConnection(DBURL,DBUSER,DBPWD);//连接数据库 Statement stmt = conn.createStatement();//数据库操作 //建表 stmt.execute("CREATE TABLE Stu5"+"(No varchar(20) PRIMARY KEY,"+"Name varchar(10),"+"Age int,"+"Sex varchar(2))"); String sqlResult = "select * from Stu5"; ResultSet rs = stmt.executeQuery(sqlResult); Query(rs); //Add stmt.executeUpdate("INSERT INTO Stu5(No,Name,Age,Sex)"+"VALUES('134','陈艳',19,'女')"); rs = stmt.executeQuery(sqlResult); Query(rs); //Change stmt.executeUpdate("UPDATE Stu5 SET Age = 20 WHERE Name = '陈艳'"); rs = stmt.executeQuery(sqlResult); Query(rs); //Delete stmt.executeUpdate("DELETE FROM Stu5 WHERE Name='陈艳'"); rs = stmt.executeQuery(sqlResult); Query(rs); rs.close(); stmt.close(); conn.close(); } }
PS:private static final String DBURL="jdbc:sqlserver://localhost:1433;DatabaseName=School1";这行代码有两个地方需要注意:
1、DBURL需要根据实际情况更改。
2、DatabaseName=School1,之前我是写的DatabaseName=‘School1’,结果错了。这个小错误,我花了好久时间找出来并改正,希望大家注意,不要和我犯同样的错误。