您的位置:首页 > 数据库

使用DDL,DML语言对数据库进行基本操作。

2012-03-23 09:54 741 查看
n 创建表并插入数据及修改数据:

import java.sql.Connection;
import java.sql.Statement;

public class CreateTable {
public static void main(String[] args) {
Connection con = null;
try {
// 通过连接池来获得一个连接
con = DBCon					.getConnectionFromPooledDataSource("jdbcPool/mydatasource");
// 创建语句对象
Statement st = con.createStatement();
// 创建表的SQL语句
String sql = "create table student(id int,name char(30),age int)";
// 执行完SQL语句的结果
boolean b = st.execute(sql);
if (b) {
System.out.println("create success");
} else {
System.out.println("create fail");
}

// 插入数据到student表
sql = "insert into student values(1,'andy',47)"
+ "insert into student values(2,'jacky',53)"
+ "insert into student values(3,'周润发',51)"
+ "insert into student values(4,'谢贤',60)";
// 执行完SQL语句的结果
b = st.execute(sql);
if (b) {
System.out.println("insert success");
} else {
System.out.println("create fail");
}

// 更新表数据
sql = "update  student set name='刘德华' where id=1";
int rows = st.executeUpdate(sql);

// 如果更新成功,rows肯定是大于1的值
if (rows > 0)
System.out.println("update success");
else
System.out.println("update fail");

} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (con != null)
con.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: