具体思路以下:
* 经过JDBC向指定的数据表中插入一条记录
1.Statement:用于执行SQL语句对象
1).经过Connection的createStatement()方法获取
2).经过executUpdate(sql)能够执行SQL语句
3).传入的sql语句能够是insert,update或者delete,但不能是select
2.Connection,Statement都是应用程序和数据库服务器的链接资源,使用后必定要关闭
须要在finally中关闭对象
3.关闭的顺序是先关闭后获取的java
这里将链接数据库的代码封装成一个类JDBCToos 方便之后的调用
JDBCTools.javasql
package com.atchance.jdbc;
import java.sql.Connection;
import java.sql.Driver;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;
public class JDBCTools {
public static void release(Statement statement, Connection con) throws SQLException{
try {
if(statement != null)
statement.close();
} catch (Exception e) {
e.printStackTrace();
}finally{
if(con != null)
con.close();
}
}
public static Connection getConnection() throws Exception{
String driverClass = "oracle.jdbc.driver.OracleDriver";
String jdbcUrl = "jdbc:oracle:thin:@localhost:1521:ORCL";
String user = "scott";
String password = "tiger";
Driver driver = (Driver)Class.forName(driverClass).newInstance();
Properties info = new Properties();
info.put("user", user);
info.put("password", password);
Connection connection = driver.connect(jdbcUrl,info);
return connection;
}
}
以后在另外一个文件里实现sql语句的增删改
JDBCTest1.java数据库
package com.atchance.jdbc;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.Driver;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;
import oracle.jdbc.*;
import oracle.jdbc.driver.*;
public class JDBCTest1 {
public void update(String sql) throws SQLException{
/** * 提取出函数实现数据库的增删改 */
Connection con = null;
Statement statement = null;
try {
con = JDBCTools.getConnection();
statement = con.createStatement();
statement.execute(sql);
} catch (Exception e) {
e.printStackTrace();
}finally{
JDBCTools.release(statement, con);
}
}
public static void main(String[] arg) throws Exception{
JDBCTest1 t1 = new JDBCTest1();
String sql = "insert into student values('0999','姓名','男','湖南')";
t1.update(sql);
}
}
以上就是实现JDBC链接oracle数据库进行增删改三种操做的代码服务器