- import java.sql.*;
- public class Test_JDBC1{
- public static void main(String args[])throws Exception{
- try{
- Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
- System.out.println("加载数据库驱动程序成功");
- }
- catch(Exception e)
- {
- System.out.println("无法加载数据库驱动程序");
- }
- //创建数据库连接
- try{
- Connection conn= DriverManager.getConnection("jdbc:sqlserver://localhost:1433;DatabaseName=students","tct","123456");
- if(!conn.isClosed())
- System.out.println("数据库连接成功!");
- //为了执行SQL语句,创建一个语句对象(Statement是一个接口),通过语句对象来执行一条SQL语句
- Statement st=conn.createStatement();
- //获取数据的记录
- String query="select * from Table1";
- //使用executeQuery()方法执行SQL命令
- ResultSet rs=st.executeQuery(query);
- System.out.println("*************************");
- while(rs.next())
- {
- System.out.print(rs.getString("name")+" ");
- System.out.print(rs.getInt("age")+" ");
- System.out.println(rs.getString("sex")+" ");
- }
- String sql="insert into Table1 values('Tom','20','man')";
- int numberOfRows = st.executeUpdate(sql);
- //String strUpdate="UPDATE Table1 SET name='tct4'";
- //int rows=st.executeUpdate(strUpdate);
- // System.out.println("数据库表中的"+rows+"行被修改了");
- //String strDelete="DELETE FROM Table1 WHERE name='Tom'";
- // int numberOfRows = st.executeUpdate(strDelete);
- //如果记录为空,加入十条记录
- /* if(resultSet.getInt()==0)
- for(int i=1;i<11;i++)
- String sql="insert into faqs value"*/
- //执行查询(select)语句,将结果放入到结果集ResultSe(接口)中 */
- query="select * from Table1";
- //使用executeQuery()方法执行SQL命令
- rs=st.executeQuery(query);
- System.out.println("*************************");
- while(rs.next())
- {
- System.out.print(rs.getString("name")+" ");
- System.out.print(rs.getInt("age")+" ");
- System.out.println(rs.getString("sex")+" ");
- }
- rs.close();
- st.close();
- conn.close();
- }
- catch(SQLException ee)
- {
- System.out.println("数据库连接失败!或存在其他问题");
- }
- }
- }
复制代码
|
|