Statement执行DDL语句

2017-06-17  本文已影响0人  常威爆打来福

一.目的

在test数据中,创建student表,包含字段id(主键),name。

核心代码:

public classDemo {

public static voidmain(String [] args){

//建立数据库url

String url="jdbc:mysql://localhost:3306/test";

String name="root";//账号

String password="root";//密码

Connection connection=null;

Statement statement=null;

try{

//创建驱动

Class.forName("com.mysql.jdbc.Driver");

//获取连接对象

connection=DriverManager.getConnection(url,name,password);

//创建statement

statement=connection.createStatement();

//准备sql语句

String sql="CREATE TABLE student (idINT PRIMARY KEY AUTO_INCREMENT ,NAMEVARCHAR(20));";

//发发送sql语句,执行sql语句,得到返回结果

intcount = statement.executeUpdate(sql);

//输出

System.out.println("链接成功"+"执行了"+count+"行");

}catch(Exception e){

System.out.println("链接失败!");

throw newRuntimeException(e);

}

finally{

//关闭链接(顺序:先打开的先关闭)

if(connection!=null){

try{

connection.close();

}catch(Exception e){

throw  newRuntimeException(e);

}}

关闭数据库

if(statement!=null){

try{

statement.close();

}catch(Exception e){

throw newRuntimeException(e);

}

}}}}

数据库核心代码
数据库关闭 运行截图 数据库查看执行结果。

注:

1.Statement接口:执行静态sql语句。

int executeUpdate(String sql):执行静态的更新sql语句(DDL,DML)

ResultSet executeQuery(String sql):执行静态的查询sql语句(DQL)

2.Connection 接口 :表示JAVA程序和数据库的连接对象。

Statment createStatement();创建Statement对象

PrepareStatement prepareStatement(Sting sql);创建PrepareStatement对象

CallableStatement prepareCall(String sql);创建prepareCall对象

上一篇 下一篇

猜你喜欢

热点阅读