【자 바】자바 에서 JDBC-ODBC 브리지 및 JDBC 드라이버 로 데이터베이스 연결 실례
/** * @author YanChengwei * */ public class DBConnect { /** * @param args */ public static void main(String[] args) { Connection con = null;// 연결 Statement stmt=null;/실행 문 ResultSet rst=null;/결과 집합
try { /*********JDBC-ODBC 브리지 로 Oacle type 1********************//연결 Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); // con = DriverManager.getConnection("jdbc:odbc:Oracledsn","myuser2","myuser2");//Oracledsn 은 dsn(데이터 원본)의 이름 입 니 다.
/********JDBC 드라이버 로 Oacle type 2 and type 4***************/연결 // 로드 드라이버 Class.forName("oracle.jdbc.driver.OracleDriver"); // 연결 만 드 는 방법 1 JDBC thin 드라이버 로 연결 type 2 만 들 기 con = DriverManager.getConnection( "jdbc:oracle:thin:@192.168.1.110:1521:ORCL", "MYUSER2","myuser2");//메모:이 문장의 IP 는 localhost 로 바 꿀 수 없습니다.그렇지 않 으 면 Network Adepter 이상 이 발생 할 수 있 습 니 다. // 연결 만 드 는 방법 2 JDBC oci 드라이버 로 연결 만 들 기 type 4 // "jdbc:oracle:oci8:@192.168.1.110:1521:ORCL", // "myuser1","myuser1");
/** ***************** 실행 문 구 를 만 드 는 방법 1**********************/ stmt = con.createStatement();
rst = stmt.executeQuery("select * from mytable2");
// 출력 결과 while (rst.next()) { System.out.print(rst.getString("stuNumber") + " "); System.out.print(rst.getString("stuName") + " "); System.out.print(rst.getString("stuAddress") + " "); System.out.print(rst.getString("stuGender") + " "); System.out.println(rst.getString("stuAge") + " "); }
// 대상 닫 기 stmt.close(); con.close(); } catch (ClassNotFoundException cnf) { System.out.println("드라이버 를 찾 을 수 없습니다"); cnf.printStackTrace();
} catch (SQLException se) { se.printStackTrace(); } } }
자바 jdbc-odbc 다 리 를 통 해 my sql 과 연결
1.my sql 명령 행 을 열 고 password root 를 입력 하 십시오.
명령 행 에 create database my sqldata 를 입력 하 십시오.
그리고 명령 행 에 use my sqldata 를 입력 하 십시오.
명령 줄 에 입력:create table student
(id int primary key,
name varchar(10),
mark int
);
Query ok 을 표시 하면 생 성 에 성 공 했 습 니 다.
2.데이터 원본 추가
"제어 판"을 열 고"관리 도구","데이터 원본"으로 이동 하지만 시스템 DSN 에는 MySql Driver 가 없습니다.MySql 의 ODBC 를 설치 해 야 합 니 다.먼저 열다http://www.mysql.com,다운 로드 를 열 고 MySql 커 넥 터/ODBC 5.1 다운 로드 를 찾 아 windows MSI Installer(x86)를 열 고 다운 로드 를 클릭 하면 MySql 의 ODBC 를 다운로드 할 수 있 습 니 다.JDBC-ODBC 다 리 를 설치 한 후 아까'시스템 데이터 원본'에서 추 가 를 클릭 하면'MsSQL ODBC 5'가 표 시 됩 니 다.1 Driver,선택 하고 나 오 는 창 에 입력:데이터 원본 이름:mysqldata
Host/Server Name(or IP) :localhost
Database Name:mysaldata
Port(3306)
확인 을 누 르 면 만 듭 니 다.
3.lomboz-eclipse 에서 클래스 를 편집 합 니 다.
eclipse,프로젝트 MyTest 의 자바 리 소스:src 에서 오른쪽 단 추 를 누 르 고 자바 류 를 만 듭 니 다.
package chapter10; import java.sql.*; public class MySqlJdbcOdbc {
public static void main(String[] args) { new MySqlJdbcOdbc().launch(); } public void launch(){ String driver="sun.jdbc.odbc.JdbcOdbcDriver"; String url="jdbc:odbc:mysqldata"; String query,name; int mark; Connection conn=null; Statement statement=null; ResultSet rs=null; try{ Class.forName(driver); } catch(ClassNotFoundException e){System.out.println("지정 한 드라이버 를 찾 을 수 없습니다");}try{ conn=DriverManager.getConnection(url); statement=conn.createStatement(); query="select * from student"; rs=statement.executeQuery(query); while(rs.next()) { name=rs.getString("name"); mark=rs.getInt("mark"); System.out.println("이름:"+name);System.out.println("성적:"+mark);}}catch(SQLException e) { e.printStackTrace(); } catch(Exception e) { e.printStackTrace(); } finally{ try{ if(rs!=null) rs.close(); if(statement!=null) statement.close(); if(conn!=null) conn.close(); } catch(SQLException e) { e.printStackTrace(); } } } } 실행:run as:java application
4.위의 연결 방식 은 JDBC-ODBC 다리 이 고 아래 의 연결 방식 은 MySql 이 제공 하 는 JDBC 다리 에서 데이터 베 이 스 를 직접 연결 하 는 방법 입 니 다.여 기 는 JDBC 다 리 를 사용 해 야 합 니 다.http://www.mysql.com위 에서 다운로드 에 필요 한 드라이버 를 찾 고 downloads 를 찾 습 니 다.Drivers and Connectors 아래 에서 MySql Connector/J-for connecting to MySql from Java 를 찾 아 압축 패 키 지 를 다운로드 하 십시오.주의:압축 패 키 지 는 windows 를 위 한 JDBC 드라이브 이 고,tar.gz 는 Liux 를 위 한 JDBC 드라이버 입 니 다.압축 을 풀 면 rec/ort/gjt/mm.my sql 에 Driver 류 파일 이 있 습 니 다.즉,eclipse 에 가 져 올 드라이버 입 니 다.
다운로드 한 압축 패 키 지 를 풀 고 JDBC 로 연결 하 는 방법 을 알 고 싶다 면?도움말 문 서 를 찾 으 려 고 합 니 다.압축 해제 폴 더 를 찾 아 docs 폴 더 를 열 고 HTML 파일 을 찾 아 열 어 보 는 것 입 니 다.
import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; Connection conn = null; ... try { conn = DriverManager.getConnection("jdbc:mysql://localhost/test?" + "user=monty&password=greatsqldb"); // Do something with the Connection ... } catch (SQLException ex) { // handle any errors System.out.println("SQLException: " + ex.getMessage()); System.out.println("SQLState: " + ex.getSQLState()); System.out.println("VendorError: " + ex.getErrorCode());
}
, ,The name of the class that implements java.sql.Driver in MySql Connector/J is com.mysql.jdbc.Driver.The org.gjt.mm.mysql.Driver class is also usable to remain backward-compatible with MM.MySql. You should use this class name when registering the driver,or when otherwise configuring software in use MySql connector/J.
The JDBC URL format for MySql Connector/J is as follows, with items in square brackets being optional:
jdbc:sql://[host][,failoverhost...][:port]/[database]
[?propertyName][=propertyValue][&propertyName2][=propertyValue2]....
If the hostname is not specified,it defaults to 127.0.0.1.if the port is not specified,it defaults to 3306,the default port number for MySql servers.
5。1。1Connectiong to MySql Using the DriverManager Interface
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class LoadDriver{
public static void main(String[] args){
try{
Clss.forName("com.mysql.jdbc.Driver").newInstance();
}
catch(Exception e){
//handle the error.
import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; Connection conn = null; ... try { conn = DriverManager.getConnection("jdbc:mysql://localhost/test?" + "user=monty&password=greatsqldb"); // Do something with the Connection ... } catch (SQLException ex) { // handle any errors System.out.println("SQLException: " + ex.getMessage()); System.out.println("SQLState: " + ex.getSQLState()); System.out.println("VendorError: " + ex.getErrorCode()); }
자바 외부 jar 파일 가 져 오기,프로젝트 루트 디 렉 터 리 에서 property 를 우 클릭 하고"Java Build Path"를 선택 하고"Add external jars",ok
또는 프로젝트 루트 디 렉 터 리 에서 오른쪽 클릭 하여"build path"를 선택 하고 properties for MyTest 창 에서 Libraries 표지 판 을 찾 습 니 다.Add External JARs 를 클릭 하여 e:/설치 소프트웨어/my sql 설치 프로그램 클립/my sql-connector-java-5.1.7/my sql-connector-java-5.1.7-bin.jar 를 클릭 하여 엽 니 다.Ok.
혹은 debug 의 이 jar 가 있 습 니 다.그것 은 디 버 깅 정보 가 있 는 것 도 좋 습 니 다.
import java.sql.*; public class MySqlJdbc {
public static void main(String[] args) { new MySqlJdbc().launch(); } public void launch(){ //String driver="sun.jdbc.odbc.JdbcOdbcDriver"; //String url="jdbc:odbc:mysqldata"; String driver="org.gjt.mm.mysql.Driver"; String url="jdbc:mysql://localhost:3306/mysqldata?user=root;password=root"; String query,name; int mark; Connection conn=null; Statement statement=null; ResultSet rs=null; try{ Class.forName(driver);
//Class.forName(driver).newInstance(); } catch(ClassNotFoundException e){System.out.println("지정 한 드라이버 를 찾 을 수 없습니다");}try{ conn=DriverManager.getConnection(url); statement=conn.createStatement(); query="select * from student"; rs=statement.executeQuery(query); //String str="insert into student values('20021213','12','52')"; //statement.executeUpdate(str); while(rs.next()) { name=rs.getString("name"); mark=rs.getInt("mark"); System.out.println("이름:"+name);System.out.println("성적:"+mark);}}catch(SQLException e) { e.printStackTrace(); } catch(Exception e) { e.printStackTrace(); } finally{ try{ if(rs!=null) rs.close(); if(statement!=null) statement.close(); if(conn!=null) conn.close(); } catch(SQLException e) { e.printStackTrace(); } } } }
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
Is Eclipse IDE dying?In 2014 the Eclipse IDE is the leading development environment for Java with a market share of approximately 65%. but ac...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.