日期:2014-05-16 浏览次数:20394 次
package com.enhance.jdbc; import java.io.FileInputStream; import java.sql.Connection; import java.sql.DriverManager; import java.sql.Statement; import java.util.Properties; /** * SQL语句的分类 * select 语句 * DML:(Data Manipulation Language)数据操作语言:检索 select 和 更新insert update delete * DDL:(Data Definition Language)数据定义语言: create alter drop truncate * DCL:(Data Control Language)数据控制语言:grant revoke * 事物控制语句:commit rollback savepoint * * * executeQuery 执行 select语句 返回 resultSet * executeUpdate 执行 DML: update delete insert 返回受影响的行数,DDL: create drop alter 返回0 * execute 执行所有的sql语句 返回 boolean ,true:表示返回 resultset结果集, false:表示返回受影响的行数 * @author Bin * */ public class ExecuteDDL { private String driver; private String url; private String user; private String pass; private Connection conn; private Statement stmt; public void initParam(String paramFile) throws Exception{ Properties prop=new Properties(); prop.load(new FileInputStream(paramFile)); driver=prop.getProperty("driver"); url=prop.getProperty("url"); user=prop.getProperty("user"); pass=prop.getProperty("pass"); } public void createTable(String sql) throws Exception{ try { Class.forName(driver); conn=DriverManager.getConnection(url,user,pass); stmt=conn.createStatement(); stmt.executeUpdate(sql); } finally{ if(stmt!=null) stmt.close(); if(conn!=null) conn.close(); } } /** * 采用 executeUpdate * 执行 DML 数据操作语言 中的 更新 语句 即 insert update delete 返回受影响的行数 * 执行 DDL 数据定义语言 create alter drop truncate 返回 "0" * @param sql * @return * @throws Exception */ public int executeDmlAndDdl(String sql)throws Exception{ try { Class.forName(driver); conn=DriverManager.getConnection(url,user,pass); stmt=conn.createStatement(); return stmt.executeUpdate(sql); } finally{ if(stmt!=null) stmt.close(); if(conn!=null) conn.close(); } } public static void main(String[] args) throws Exception { ExecuteDDL ed=new ExecuteDDL(); //System.out.println(System.getProperty("user.dir")); ed.initParam("src/mysql.ini"); /*ed.createTable("create table jdbc_test" + "( jdbc_id int auto_increment primary key," + "jdbc_name varchar(255)," + "jdbc_desc text);");*/ //System.out.println(ed.executeDmlAndDdl("select host,user,password from user")); ed.executeDmlAndDdl("create table img_table" + "(img_id int auto_increment primary key," + "img_name varchar(255)," + "img_data mediumblob);"); System.out.println("---------建表成功-------"); } }