connection con=this.creatcon();//获得连接
preparedstatement pstm=null;//命令器
string sql=insert into student(student_id,name,sex,age) values(?,?,?,?);//设置要执行的sql语句
pstm=con.preparestatement(sql);//准备执行sql语句命令
pstm.setstring(2, name);//设置第2个问号的值
pstm.setstring(3, sex);//设置第3个问号的值
pstm.setint(4, age);//设置第4个问号的值
pstm.setint(1,student_id);//设置第1个问号的值
//pstm.executequery();//执行sql命令,这个命令是在查询的时候,返回数据集resultset
pstm.executeupdate();//执行sql命令,当是插入,,删除,修改的时候用
system.out.println(写入成功);//执行后写出是否成功
连接的打开和关闭:
// 创建一个连接oracle数据库的类
public static connection creatcon()
{
string username=scott;
string password=tiger;
connection con=null;
try
{
class.forname(oracle.jdbc.driver.oracledriver);
string url=java:oracle:thin:@localhost:1521:ora9i;//连接oracle数据库
/*class.forname(com.micrsoft.jdbc.sqlserver.sqlserverdriver);
string url=java:microsoft:sqlserver://localhost:1433;//连接sql server数据库*/
con=(connection)drivermanager.getconnection(url,username,password);
return con;
}
catch(exception exc)
{
system.out.println(exc);
}
return null;
}
//关闭连接
public void closecon(connection c)
{
try
{
c.close();
}
catch(exception c1)
{
system.out.println(c1);
}
}
