How to use Jdbc to connect to different databases
Today, I will talk to you about how to use Jdbc to connect to different databases. Many people may not know much about it. In order to make you understand better, the editor has summarized the following content for you. I hope you can get something according to this article.
1.Jdbc connects to Access database
① select the system DNS tab through Control Panel > > Administrative tools > > data Source, add Microsoft Access Driver (* .mdb), and take the data source name sample as an example, select the database file. The link code in the program is as follows:
Public static Connection getConnection () {
Try {
Class.forName ("sun.jdbc.odbc.JdbcOdbcDriver")
Connection conn = DriverManager.getConnection ("jdbc:odbc:sample", "", "); / / this connection requires the establishment of a data source called sample
} catch (ClassNotFoundException e) {
E.printStackTrace ()
} catch (SQLException e) {
E.printStackTrace ()
}
Return conn
}
② establishes the connection directly in the program. The code is as follows:
Public static Connection getConnection () {
Try {
String url = "jdbc:odbc:driver= {Microsoft Access Driver (* .mdb)}; DBQ=D://Documents and Settings//Administrator//workspace//sample.mdb"
/ / the absolute path of the database to be given in url
Class.forName ("sun.jdbc.odbc.JdbcOdbcDriver")
Conn = DriverManager.getConnection (url, ",")
} catch (ClassNotFoundException e) {
E.printStackTrace ()
} catch (SQLException e) {
E.printStackTrace ()
}
Return conn
}
2.Jdbc connects to the MySQL database (requires a driver that introduces mysql)
Public static Connection getConnection () {
Try {
Class.forName ("com.mysql.jdbc.Driver")
Conn = DriverManager.getConnection (
"jdbc:mysql://localhost:3306/bookstore?user=root&password=&characterEncoding=utf-8"); / / bookstore is the name of your database
} catch (ClassNotFoundException e) {
E.printStackTrace ()
} catch (SQLException e) {
E.printStackTrace ()
}
Return conn
}
3.Jdbc connects to the Oracle database (requires classes12, a driver for Oracle)
Public static Connection getConnection () {
Try {
Class.forName ("oracle.jdbc.driver.OracleDriver")
Conn = DriverManager.getConnection (
"jdbc:oracle:thin:@localhost:1521:oracle9i", "scott", "tiger"); / / oracle9i is the database name
} catch (ClassNotFoundException e) {
E.printStackTrace ()
} catch (SQLException e) {
E.printStackTrace ()
}
Return conn
}
After reading the above, do you have any further understanding of how to use Jdbc to connect to different databases? If you want to know more knowledge or related content, please follow the industry information channel, thank you for your support.