JDBC_수업 자체 코드
Oracle
package tarena;
import java.sql.*;
public class lab1 {
public static void main(String[] args) {
Connection con = null;
try {
//
String driverName = "oracle.jdbc.driver.OracleDriver";
Class.forName(driverName);
//
String url = "jdbc:oracle:thin:@192.168.7.88" + ":1521:tarena";
String username = "rensx";
String pwd = "rensx";
con = DriverManager.getConnection(url, username, pwd);
System.out.println("con->" + con);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
con.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
/////////////////////////////////////////////////////////////////
MySQL
package tarena;
import java.sql.*;
public class lab1 {
public static void main(String[] args) {
Connection con = null;
try {
//
String driverName = "com.mysql.jdbc.Driver";
Class.forName(driverName);
//
String url = "jdbc:mysql://127.0.0.1:3306/mydb";
String username = "root";
String pwd = "";
con = DriverManager.getConnection(url, username, pwd);
System.out.println("con->" + con);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
con.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
con->com.mysql.jdbc.Connection@ae506e
////////////////////////////////////////////////
package tarena;
import java.sql.*;
public class lab4{
public static void main(String[] args) {
Connection con = null;
Statement stmt = null;
ResultSet re = null;
try { //1
String driverName = "oracle.jdbc.driver.OracleDriver";
Class.forName(driverName);
//2
String url = "jdbc:oracle:thin:@192.168.7.88" + ":1521:tarena";
String username = "rensx";
String pwd = "rensx";
con = DriverManager.getConnection(url, username, pwd);
//3
stmt =con.createStatement();
//4SQL
String sql= "drop table ren_sql";
stmt.executeUpdate(sql);/**executeUpdate SQL , INSERT、UPDATE DELETE , SQL ( SQL DDL )*/
sql= "create table ren_sql(name varchar2(20),id number(10) )";
stmt.executeUpdate(sql);
sql="insert into ren_sql values('ren1',20)";
stmt.executeUpdate(sql);
sql="insert into ren_sql values('ren2',20)";
stmt.executeUpdate(sql);
sql="insert into ren_sql values('ren3',20)";
stmt.executeUpdate(sql);
sql="select * from ren_sql";
re=stmt.executeQuery(sql);//executeQuery SQL , ResultSet
System.out.println("re->"+re);
//5
StringBuffer sb=new StringBuffer();
while(re.next()){
sb.append("name:"+re.getString(1)+" ");
sb.append("id:"+re.getInt(2)+"
");
}
System.out.println(sb);
} catch (Exception e) {
e.printStackTrace();
} finally {
//6
try {
if(re!=null)re.close();//
} catch (Exception e) {
e.printStackTrace();
}
try {
if(stmt!=null)stmt.close();//
} catch (Exception e) {
e.printStackTrace();
}
try {
if(con!=null)con.close();//
} catch (Exception e) {
e.printStackTrace();
}
}//finally
}
}
//////////////////////////////////////////////////
package tarena;
import java.sql.*;
public class JdbcUtil{
static {
try{
String driverName="oracle.jdbc.driver.OracleDriver";
Class.forName(driverName);}catch(Exception e){e.printStackTrace();}
}//static
public static Connection getConnection(){
String url = "jdbc:oracle:thin:@192.168.7.88" + ":1521:tarena";
String username = "rensx";
String pwd = "rensx";
Connection con=null;
try{
con = DriverManager.getConnection(url, username, pwd);
}catch(Exception e){e.printStackTrace();}
return con;
}
public static void release(ResultSet rs,Statement stmt,Connection con){
try{if(rs!=null){rs.close();}}catch(Exception e){e.printStackTrace();}
try{if(stmt!=null){stmt.close();}}catch(Exception e){e.printStackTrace();}
try{if(con!=null){con.close();}}catch(Exception e){e.printStackTrace();}
}
public static void release(Object obj){
try{if(obj instanceof ResultSet){((ResultSet)obj).close();}
else if(obj instanceof Statement){((Statement)obj).close();}
else if(obj instanceof Connection){((Connection)obj).close();}
}catch(Exception e){e.printStackTrace();}
}
public static void resultSetMD(ResultSet rs) {//
// public static void printRs(ResultSet rs){
if(rs==null){
System.out.println("ResultSet is null!");
return;
}
try{
ResultSetMetaData md = rs.getMetaData();
int cols = md.getColumnCount();
StringBuffer sb = new StringBuffer();
while(rs.next()){
for(int i=1;i<=cols;i++){
sb.append(md.getColumnName(i)+"=");
sb.append(rs.getString(i)+" ");
}
sb.append("
");
}
System.out.println(sb.toString());
}catch(Exception e){
e.printStackTrace();
}
}
}
////////////////////////////////////////////////
PreparedStatement
package tarena;
import java.sql.*;
public class lab6{
public static void main(String [] args){
Connection con=null;
PreparedStatement ps=null;
ResultSet re = null;
try{
con = JdbcUtil.getConnection();
String sql="insert into ren_sql values(?,?)";
ps=con.prepareStatement(sql);
for(int i=0;i<10;i++){ps.setString(1,"ren"+i);ps.setInt(2,i);ps.executeUpdate();}
JdbcUtil.release(ps);//
sql="select * from ren_sql";
ps=con.prepareStatement(sql);
re=ps.executeQuery();
StringBuffer sb=new StringBuffer();
while(re.next()){
sb.append("name:"+re.getString(1)+" ");
sb.append("is:"+re.getString(2)+"
");
}
System.out.println(sb);
}catch(Exception e){}
finally{JdbcUtil.release(re,ps,con);}
}
}
////////////////////////////////////////////
ResultSetMetaData
package tarena;
import java.sql.*;
public class lab7{
public static void main(String [] args){
if(args.length!=1){System.out.println("error");return ;}
String tableName=args[0];
Connection con=null;
PreparedStatement ps=null;
ResultSet re = null;
try{
con = JdbcUtil.getConnection();
String sql="select * from "+tableName;
ps=con.prepareStatement(sql);
re=ps.executeQuery();
StringBuffer sb=new StringBuffer();
ResultSetMetaData md =re.getMetaData();
int cols =md.getColumnCount();
System.out.println("cols:"+cols);
for(int i=1;i<=cols;i++){
sb.append(md.getColumnName(i)+"->");
sb.append(md.getColumnType(i)+"&");//
sb.append(md.getColumnTypeName(i)+"
");//
}
sb.append("
");
while(re.next()){
for(int i=1;i<=cols;i++){
sb.append(md.getColumnName(i)+"=");
sb.append(re.getString(i));
sb.append(" ");
}
sb.append("
");
}
System.out.println(sb);
}catch(Exception e){}
finally{JdbcUtil.release(re,ps,con);}
}
}
////////////////////////////////////////////////
DatabaseMetaData
package tarena;
import java.sql.*;
public class Lab9
{
public static void main(String[] args){
Connection con = null;
ResultSet rs =null;
try{
con = JdbcUtil.getConnection();
DatabaseMetaData md = con.getMetaData();
String[] types = {"TABLE"};
rs = md.getTables(
null,
"OPENLAB",
"%",
types);
JdbcUtil.printRs(rs);
}catch(Exception e){
e.printStackTrace();
}finally{
JdbcUtil.release(rs,null,con);
}
}
}
///////////////////////////////////////////////
package tarena;
import java.sql.*;
import java.io.*;
public class SQLTools
{
public static void main(String[] args){
Connection con = null;
while((con=getConnection())==null){}
try{
StringBuffer sb = new StringBuffer();
String cmd = "";
boolean flag = true;
int c = 0;
String message = "";
while(flag){
if(c++==0){
message = "SQLTools->";
}else{
message = c+"->";
}
sb.append(prompt(message));
cmd = sb.toString().trim();
if(cmd.endsWith(";")){
String sql = cmd.substring(0,cmd.length()-1);
if("quit".equals(sql)){
flag = false;
}else{
System.out.println(sql);
execute(sql,con);
sb = new StringBuffer();
c=0;
}
}
}
}catch(Exception e){
e.printStackTrace();
}finally{
JdbcUtil.release(con);
}
}
public static Connection getConnection(){
try{
String driverName="oracle.jdbc.driver.OracleDriver";
Class.forName(driverName);}catch(Exception e){e.printStackTrace();}
String message=" url:
";
String url = prompt(message);
message = " :
";
String username = prompt(message);
message = " :
";
String pwd = prompt(message);
Connection con = null;
try{
con = DriverManager.getConnection(
url,username,pwd);
}catch(Exception e){
System.out.println("-> !");
}
return con;
}
public static String prompt(String message){
BufferedReader in =
new BufferedReader(
new InputStreamReader(System.in));
System.out.print(message);
String input = "";
try{
input=in.readLine();
}catch(Exception e){
e.printStackTrace();
}
return input;
}
public static void execute(String sql,Connection con){
Statement stmt = null;
ResultSet rs = null;
int c = 0;
try{
stmt = con.createStatement();
if(stmt.execute(sql)){
rs = stmt.getResultSet();
JdbcUtil.resultSetMD(rs);
}else{
c = stmt.getUpdateCount();
System.out.println(" -"+c);
}
}catch(Exception e){
System.out.println(" !");
}finally{
JdbcUtil.release(rs,stmt,null);
}
}
}
////////////////////////////////////////////////
package tarena;
import java.io.FileNotFoundException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.List;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.input.SAXBuilder;
public class ConnectionFactory {
private static String url;
private static String userName;
private static String passwd;
private static String driver;
static {
try {
parseConfig();
Class.forName(driver);
} catch (Exception e) {
e.printStackTrace();
}
}
public static synchronized Connection getConnection() throws SQLException {
return DriverManager.getConnection(url,userName,passwd);
}
private static void parseConfig() throws FileNotFoundException {
SAXBuilder builder = new SAXBuilder();
Document dom = null;
try {
dom = builder.build("dbconfig.xml");
} catch (Exception e) {
throw new FileNotFoundException("file");
}
Element root = dom.getRootElement();
String use = root.getAttributeValue("use");
List<Element> infos = root.getChildren();
for (Element info : infos) {
if (use.equals(info.getAttributeValue("name"))) {
List<Element> values = info.getChildren();
for (Element value : values) {
if ("url".equals(value.getName())) {
url = value.getTextTrim();
} else if ("username".equals(value.getName())) {
userName = value.getTextTrim();
} else if ("passwd".equals(value.getName())) {
passwd = value.getTextTrim();
} else if ("driver".equals(value.getName())) {
driver = value.getTextTrim();
}
}
}
}
}
public static void main(String[] args) {
new ConnectionFactory();
}
}
/**
* <?xml version="1.0" encoding="UTF-8"?>
<dbconfig use="oracle">
<dbinfo name="oracle">
<url>jdbc:oracle:thin:@192.168.7.88:1521:tarena</url>
<username>rensx</username>
<passwd>rensx</passwd>
<driver>oracle.jdbc.driver.OracleDriver</driver>
</dbinfo>
<dbinfo name="mysql">
<url>jdbc:mysql://127.0.0.1:3306/test</url>
<username>root</username>
<passwd></passwd>
<driver>com.mysql.jdbc.Driver</driver>
</dbinfo>
</dbconfig>*/
///////////////////////////////////////////////////////////
3
package tarena;
import java.sql.*;
import java.io.*;
public class SQLTools
{ //
public static void main(String[] args){
Connection con = null;
while((con=getConnection())==null){}
try{
//
con.setAutoCommit(false);
StringBuffer sb = new StringBuffer();
String cmd = "";
boolean flag = true;
int c = 0;
String message = "";
while(flag){
if(c++==0){
message = "SQLTools->";
}else{
message = c+"->";
}
sb.append(prompt(message));
cmd = sb.toString().trim();
if(cmd.endsWith(";")){
String sql = cmd.substring(0,cmd.length()-1);//
if("quit".equals(sql)){
flag = false;
con.commit();//
}else if("commit".equals(sql)){
con.commit();
c=0;
}else if("roolback".equals(sql)){
con.rollback();
c=0;
}else{
System.out.println(sql);
try{ execute(sql,con);}catch(Exception e){
System.out.println(" ");
try{
if(con!=null){con.rollback();}
}catch(Exception ee){}
}
sb = new StringBuffer();
c=0;
}
}
}
}catch(Exception e){
e.printStackTrace();
}finally{
JdbcUtil.release(con);
}
}
public static Connection getConnection(){
try{
String driverName="oracle.jdbc.driver.OracleDriver";
Class.forName(driverName);}catch(Exception e){e.printStackTrace();}
String message=" url:
";
String url = prompt(message);
message = " :
";
String username = prompt(message);
message = " :
";
String pwd = prompt(message);
Connection con = null;
try{
con = DriverManager.getConnection(
url,username,pwd);
}catch(Exception e){
System.out.println("-> !");
}
return con;
}
public static String prompt(String message){
BufferedReader in =
new BufferedReader(
new InputStreamReader(System.in));
System.out.print(message);
String input = "";
try{
input=in.readLine();
}catch(Exception e){
e.printStackTrace();
}
return input;
}
public static void execute(String sql,Connection con) throws Exception{
Statement stmt = null;
ResultSet rs = null;
int c = 0;
try{
stmt = con.createStatement();
if(stmt.execute(sql)){
rs = stmt.getResultSet();
JdbcUtil.resultSetMD(rs);
}else{
c = stmt.getUpdateCount();
System.out.println(" -"+c);
}
}catch(Exception e){
System.out.println(" !");
throw e;
}finally{
JdbcUtil.release(rs,stmt,null);
}
}
}
/////////////////////////////////////////////////////////
public class lab10 {
public static void main(String[] args) {
Connection con =null;
try{
con=JdbcUtil.getConnection();
con.setTransactionIsolation(Connection.TRANSACTION_NONE);
// :java.sql.SQLException: READ_COMMITTED SERIALIZABLE
}catch(Exception e){
e.printStackTrace();
}finally{
JdbcUtil.release(con);
}
}
}
//////////////////////////////////////////
public class lab11 {
//JDBC2.0
public static void main(String[] args) {
Connection con = null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
con = JdbcUtil.getConnection();
con.setAutoCommit(false);//
String sql = "select * from ren_sql";
//
ps = con.prepareStatement(sql, ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_UPDATABLE);
rs = ps.executeQuery();
JdbcUtil.resultSetMD(rs);
if(rs.isAfterLast()){
System.out.println(" ");
rs.beforeFirst();
}
JdbcUtil.resultSetMD(rs);
con.commit();
} catch (Exception e) {
e.printStackTrace();
try{
if(con!=null){con.rollback();}
}catch(Exception ee){}
}finally{
JdbcUtil.release(rs, ps, con);
}
}
}
////////////////////////////////////////////
public class lab12 {
//JDBC2.0
public static void main(String[] args) {
Connection con = null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
con = JdbcUtil.getConnection();
con.setAutoCommit(false);//
String sql = "select id,mon from ren_bank";// *
//
ps = con.prepareStatement(sql, ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_UPDATABLE);
rs = ps.executeQuery();
//
rs.moveToInsertRow();
rs.updateInt(1,3);
rs.updateDouble(2,100);
rs.insertRow();
rs.moveToCurrentRow();
//
System.out.println("*************1**********");
JdbcUtil.resultSetMD(rs);
con.commit();
System.out.println("**************2***************");
JdbcUtil.release(rs);
rs=ps.executeQuery();
JdbcUtil.resultSetMD(rs);
con.commit();
} catch (Exception e) {
e.printStackTrace();
try{
if(con!=null){con.rollback();}
}catch(Exception ee){}
}finally{
JdbcUtil.release(rs, ps, con);
}
}
}
////////////////////////////////////////
package tarena;
import java.sql.*;
//
public class SQLTools { //
public static void main(String[] args) {
Connection con = null;
while ((con = getConnection()) == null) {
}
try {
//
con.setAutoCommit(false);
StringBuffer sb = new StringBuffer();
String cmd = "";
boolean flag = true;
int c = 0;
String message = "";
while (flag) {
if (c++ == 0) {
message = "SQLTools->";
} else {
message = c + "->";
}
sb.append(prompt(message));
cmd = sb.toString().trim();
if (cmd.endsWith(";")) {
String sql = cmd.substring(0, cmd.length() - 1);//
if ("quit".equals(sql)) {
flag = false;
con.commit();//
} else if ("commit".equals(sql)) {
con.commit();
c = 0;
} else if ("roolback".equals(sql)) {
con.rollback();
c = 0;
} else {
System.out.println(sql);
try {
execute(sql, con);
} catch (Exception e) {
System.out.println(" ");
try {
if (con != null) {
con.rollback();
}
} catch (Exception ee) {
}
}
sb = new StringBuffer();
c = 0;
}
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
JdbcUtil.release(con);
}
}
public static Connection getConnection() {
try {
String driverName = "oracle.jdbc.driver.OracleDriver";
Class.forName(driverName);
} catch (Exception e) {
e.printStackTrace();
}
String message = " url:
";
String url = prompt(message);
message = " :
";
String username = prompt(message);
message = " :
";
String pwd = prompt(message);
Connection con = null;
try {
con = DriverManager.getConnection(url, username, pwd);
} catch (Exception e) {
System.out.println("-> !");
}
return con;
}
public static String prompt(String message) {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
System.out.print(message);
String input = "";
try {
input = in.readLine();
} catch (Exception e) {
e.printStackTrace();
}
return input;
}
public static void execute(String sql, Connection con) throws Exception {
Statement stmt = null;
ResultSet rs = null;
int c = 0;
try {
stmt = con.createStatement();
if (stmt.execute(sql)) {
rs = stmt.getResultSet();
JdbcUtil.resultSetMD(rs);
} else {
c = stmt.getUpdateCount();
System.out.println(" -" + c);
}
} catch (Exception e) {
System.out.println(" !");
throw e;
} finally {
JdbcUtil.release(rs, stmt, null);
}
}
}
///////////////////////////////////////
////////////////////////////////////
4
public class lab13 {
//
public static void main(String[] args) {
Connection con = null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
con = JdbcUtil.getConnection();
con.setAutoCommit(false);
String sql = "insert into ren_bank values(?,?)";
ps = con.prepareStatement(sql);
System.out.println("now=1" + new java.util.Date());
for (int i = 0; i < 1000; i++) {
ps.setInt(1, i);
ps.setDouble(2, i);
//ps.executeUpdate();
// , 100
ps.addBatch();
if(i%100==0){ps.executeBatch();}
}
con.commit();
System.out.println("now=2" + new java.util.Date());
} catch (Exception e) {
e.printStackTrace();
try {
if (con != null)
con.rollback();
} catch (Exception ee) {
} finally {
JdbcUtil.release(rs, ps, con);
}
}
}
}
////////////////////////////////////////
Blob
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.sql.Blob;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
public class lab14 {
// JDBC2.0
public static void main(String[] args) {
Connection con = null;
PreparedStatement ps = null;
ResultSet rs = null;
Blob b = null;
int id = 1;
String filename = args[0];//
System.out.println("filename="+filename);
try {
con = JdbcUtil.getConnection();
con.setAutoCommit(false);
// 1 oracle blob
String sql = "insert into ren_blob values(?,?,empty_blob())";// oracle
//
ps = con.prepareStatement(sql);
ps.setInt(1, id);
ps.setString(2, filename);
ps.executeUpdate();
// 2 blob blob
sql = "select fileContent from ren_blob where id=? for update";//
JdbcUtil.release(ps);
ps = con.prepareStatement(sql);
ps.setInt(1, id);
rs = ps.executeQuery();
if (rs.next()) {
b = rs.getBlob(1);
}
// 3 blob
InputStream in = new FileInputStream(filename);
OutputStream out = b.setBinaryStream(0);
byte[] content = new byte[in.available()];
in.read(content);
out.write(content);
in.close();
out.close();
// 4 blob
sql = "update ren_blob set fileContent=? where id=?";
JdbcUtil.release(rs, ps, null);
ps = con.prepareStatement(sql);
ps.setBlob(1, b);
ps.setInt(2, id);
ps.executeUpdate();
con.commit();
} catch (Exception e) {
e.printStackTrace();
try {
if (con != null)
con.rollback();
} catch (Exception ee) {
}
} finally {
JdbcUtil.release(null, ps, con);
}
}
}
/**
* create table ren_blob( id number(12) primary key, filename varchar(55) not
* null, fileContent blob );
*/
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.sql.Blob;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
public class lab142 {
public static void main(String[] args) {
Connection con = null;
PreparedStatement ps = null;
ResultSet rs = null;
Blob b = null;
int id = 1;
String filename = args[0];//
if (args.length != 1) {
System.out.println(" ");
}
try {
con = JdbcUtil.getConnection();
con.setAutoCommit(false);
// 1 id blob
String sql = "select fileContent from ren_blob where id=? for update";
ps = con.prepareStatement(sql);
ps.setInt(1, id);
rs = ps.executeQuery();
if (rs.next()) {
b = rs.getBlob(1);
}
// 2 blob ( )
InputStream in = b.getBinaryStream();
OutputStream out = new FileOutputStream(filename);
// error:byte[] content=new byte [in.available()];
int b2 = 0, c = 0;
while ((b2 = in.read()) != -1) {
out.write(b2);
if (++c % 1024 == 0) {
System.out.println(" ");
}
}
in.close();
out.close();
con.commit();
} catch (Exception e) {
e.printStackTrace();
try {
if (con != null)
con.rollback();
} catch (Exception ee) {
}
} finally {
JdbcUtil.release(rs, ps, con);
}
}
}
/////////////////////////////////////////////////////////////
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
activemq 5.5 의 입문 은 설치, 시작, 데이터베이스 지속 화 를 포함한다Apache ActiveMQ 5.5.0 은 주로 유지보수 버 전 으로 130 개가 넘 는 문 제 를 복 구 했 으 며 대부분 bug 와 개선 이 었 다. Improved performance for offline d...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.