JDBC对数据库的简单操作
时间:2021-07-01 10:21:17
帮助过:23人阅读
* 获取数据库连接
*/
public Connection GetConnection(){
Connection connection=
null;
try {
Class.forName("oracle.jdbc.driver.OracleDriver"
);
try {
connection=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:orcl","orcl_test","orcl_test"
);
} catch (SQLException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}
} catch (ClassNotFoundException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}
return connection;
}
/**
* 添加方法
*/
public boolean Add(Student stu){
Connection resConnection =
GetConnection();
String insertDataSql=String.format("insert into student(sid, sname, sage, ssex) "
+ "values (sid_seq.nextval, %s, %s, %s)"
,
"?","?","?"
);
try {
PreparedStatement addStatement =
resConnection.prepareStatement(insertDataSql);
addStatement.setString(1
, stu.getsName());
addStatement.setInt(2
, stu.getsAge());
addStatement.setString(3
, String.valueOf(stu.getsSex()));
int addRes =
addStatement.executeUpdate();
addStatement.close();
resConnection.close();
if (addRes>=0
) {
return true;
}
else{
return false;
}
} catch (SQLException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}
return false;
}
jar包:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
JDBC对数据库的简单操作
标签:str trace gets drive null todo ret java driver