读书人

Java学习札记-JDBC 1

发布时间: 2012-10-18 13:46:56 作者: rapoo

Java学习笔记-JDBC 1

Registering the Driver Class

?

There are 3 ways to register a driver to your java program.

?

1 A JAR file can be automatically register if it contains a file name META-INF/services/java.sql.Driver

?

2 Load the driver class in your java program. For example:

Class.forName("oracle.jdbc.OracleDriver");

?

3 Set jdbc.driver property. You can specify the property with a command-line argument, such as

java -Djdbc.drivers=org.postgresql.Driver ProgramName
?

System.setProperty("jdbc.drivers", "org.postgresql.Driver");

?

String url = "jdbc:postgresql:COREJAVA";String username = "dbuser";String password = "secret";Connection conn = DriverManager.getConnection(url, username, password);

?

Following code is a whole example.

?

import java.io.IOException;import java.io.InputStream;import java.sql.Connection;import java.sql.DriverManager;import java.sql.ResultSet;import java.sql.SQLException;import java.sql.Statement;import java.util.Properties;public class DBTest {    public static void main(String[] args) {                try {            runTest();        } catch (SQLException ex) {            for (Throwable t : ex) {                t.printStackTrace();            }        } catch (IOException ex) {            ex.printStackTrace();        }    }        public static void runTest() throws IOException, SQLException {                Connection conn = getConnection();                try {            Statement stat = conn.createStatement();                        stat.executeUpdate("CREATE TABLE Greetings (Message CHAR(20))");            stat.execute("INSERT INTO Greetings VALUES ('Hello, World!')");                        ResultSet result = stat.executeQuery("SELECT * FROM Greetings");                        if (result.next()) {                System.out.println(result.getString(1));            }                        result.close();            stat.executeUpdate("DROP TABLE Greetings");                    } finally {            conn.close();        }    }        public static Connection getConnection() throws IOException, SQLException {                Properties props = new Properties();        InputStream in = DBTest.class.getResourceAsStream("database.properties");        props.load(in);                String drivers = props.getProperty("jdbc.drivers");        if (drivers != null) {            System.setProperty("jdbc.drivers", drivers);        } else {            return null;        }                String url = props.getProperty("jdbc.url");        String username = props.getProperty("jdbc.username");        String password = props.getProperty("jdbc.password");                    return DriverManager.getConnection(url, username, password);    }}

?

database.properties file

?

jdbc.drivers=com.mysql.jdbc.Driverjdbc.url=jdbc:mysql:///javacorejdbc.username=rootjdbc.password=mysql
?

?

读书人网 >其他数据库

热点推荐