专注于高品质PHP技术等信息服务于一体 [STIEMAP] [RSS]

百度提供的广告:
java
当前位置:首页 > 技术文档 > java >  > 
Jdbc-Java源码

package com.qingruxu.db;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class db {
 
 public  db()
 {
  Connection conn=null;
  try {
   Class.forName("com.mysql.jdbc.Driver");
  } catch (ClassNotFoundException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
  System.out.println("加载驱动成 功");
  try {
    conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/php2?user=root&password=1");
  } catch (SQLException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
  System.out.println(" 得到数据库连接成功");
  
  PreparedStatement prstmt=null;
  Statement stmt=null;
  ResultSet rs=null;
  
  // 普通会话
  String sql="select * from admin ;";
  
  try {
   stmt=conn.createStatement();
  } catch (SQLException e1) {
   // TODO Auto-generated catch block
   e1.printStackTrace();
  }
  System.out.println(" 创建会话成功");
  try {
   rs=stmt.executeQuery(sql);
   while(rs.next())
   {
    System.out.println(rs.getString("userid"));
   }
  } catch (SQLException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
  
  //  预编译的会话
  
   sql="select * from admin where aid=?;";
  
   try {
   prstmt=conn.prepareStatement(sql);
   prstmt.setInt(1, 1);
   rs=prstmt.executeQuery();
   while(rs.next())
   {
    System.out.println(rs.getString("userid"));
   }
   
  } catch (SQLException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
   finally{
            if(rs!=null)
                try {
                    rs.close();
                } catch (SQLException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }
            if(prstmt!=null)
                try {
                    prstmt.close();
                } catch (SQLException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            if(conn!=null)
                    try {
                        conn.close();
                    } catch (SQLException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
               
        }
  
 }
 public static void main(String[] args) {
  // TODO Auto-generated method stub
  new db();

 }

}