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();
}
}
}
}