java - mysql

上一篇 / 下一篇  2012-07-24 22:19:04 / 个人分类:java

package db;
import java.sql.*;
public class database {
 /**
  * @param args
  */
 Connection conn;
 Statement statement;
 ResultSet rs;
 String driver = "com.mysql.jdbc.Driver";
 // URL指向要访问的数据库名mytest
 String url = "jdbc:mysql://localhost:3306/mytest";
 // MySQL配置时的用户名
 String user = "root";
 // Java连接MySQL配置时的密码
 String password = "root";
 
 /*连接数据库
  * 连接成功返回ture
  * 否则返回false
  * */
   public Boolean connectDB()
    {
     try {
      // 加载驱动程序
      Class.forName(driver);
      // 连续数据库
      conn = DriverManager.getConnection(url, user, password);
      if(!conn.isClosed())
          {System.out.println("Succeeded connecting to the Database!");
          return false;
          }
         
      // statement用来执行SQL语句
      statement = conn.createStatement();
             
           } catch(ClassNotFoundException e)
           {  System.out.println("Sorry,can`t find the Driver!");  
           e.printStackTrace();  
           } catch(SQLException e)
           {   e.printStackTrace();  }
           catch(Exception e)
           {  e.printStackTrace();  
           }
           return true;
     
    }
  
 /*运行select的sql语句
  * 返回值为执行结果
  * */
 public ResultSet executeSql(String sql){ 
  try {
  // 要执行的SQL语句
  statement = conn.createStatement();
  rs = statement.executeQuery(sql); 
         
       } catch(SQLException e)
       {   e.printStackTrace();  }
       catch(Exception e)
       {  e.printStackTrace();  
       }
       return rs;
       }
 
 /*运行除外select的sql语句
  *
  * */
 public void executeUID(String sql){ 
  try {
  // 要执行的SQL语句
  statement = conn.createStatement();
  statement.executeUpdate(sql);
 
       } catch(SQLException e)
       {   e.printStackTrace();  }
       catch(Exception e)
       {  e.printStackTrace();  
       }
      
       }
 /*
  *  关闭数据库
  *
  * */
 void closeDB()
 {
  try {
  rs.close(); 
     conn.close();
  } catch(SQLException e)
        {   e.printStackTrace();  }
        catch(Exception e)
        {  e.printStackTrace(); }
  
 }
 public static void main(String[] args) {
  // TODO Auto-generated method stub
  database test = new database();
  test.connectDB();
  test.executeSql( "select * from userinfo;");
  test.executeUID("insert userinfo (username,password) values('5','5');");
  test.executeUID("update userinfo set password = '00' where username='5';");
  test.closeDB();
 }
}

TAG:

 

评分:0

我来说两句

Open Toolbar