增:
import java.sql.Connection;
import java.sql.Date;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class TestInsert {
public static void main(String[] args) throws SQLException {
String url = "jdbc:oracle:thin:@localhost:1521:orcl";
String username = "system";
String pwd = "tarena";
Connection con = DriverManager.getConnection(url, username, pwd);
String sql = "insert into emp values(?,?,?,?,?,?,?,?)";
PreparedStatement prep = con.prepareStatement(sql);
prep.setInt(1, 2222);
prep.setString(2, "xiaohong");
prep.setString(3, "boss");
prep.setInt(4, 7902);
long time = System.currentTimeMillis();
prep.setDate(5, new Date(time));
prep.setDouble(6, 632.12);
prep.setDouble(7, 100.0);
prep.setInt(8, 40);
prep.executeUpdate();
con.commit();
System.out.println("插入成功");
}
}
删:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class TestDelete {
public static void main(String[] args) throws SQLException {
String url = "jdbc:oracle:thin:@localhost:1521:orcl";
String username = "system";
String pwd = "tarena";
Connection con = DriverManager.getConnection(url, username, pwd);
System.out.println(con);
String sql = "delete from emp where empno=?";
PreparedStatement prep = con.prepareStatement(sql);
prep.setInt(1, 7900);
prep.executeUpdate();
con.commit();
System.out.println("删除成功");
}
}
改:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class TestUpdate {
public static void main(String[] args) throws SQLException {
String url = "jdbc:oracle:thin:@localhost:1521:orcl";
String username = "system";
String pwd = "tarena";
Connection con = DriverManager.getConnection(url, username, pwd);
System.out.println(con);
String sql = "update emp set sal=?,comm=? where empno=?";
PreparedStatement prep = con.prepareStatement(sql);
prep.setDouble(1, 8900.1);
prep.setDouble(2, 2000);
prep.setInt(3, 2222);
prep.executeUpdate();
con.commit();
System.out.println("更改成功");
}
}
查:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class TestSelect {
public static void main(String[] args) throws SQLException {
String url = "jdbc:oracle:thin:@localhost:1521:orcl";
String username = "system";
String pwd = "tarena";
Connection con = DriverManager.getConnection(url, username, pwd);
System.out.println("获得数据库的连接为:" + con);
String sql = "select * from emp";
PreparedStatement prep = con.prepareStatement(sql);
ResultSet rs = prep.executeQuery();
while (rs.next()) {
System.out.println(rs.getInt("empno") + "," + rs.getString("ename")+ ","
+ rs.getDate("hiredate")+ "," + rs.getDouble("sal"));
}
}
}
建表操作(内含数据)可点击本处