JDBC---连接数据库

来源:互联网 发布:linux如何安装hadoop 编辑:程序博客网 时间:2024/05/29 17:30

1.加载驱动类到内存
2.获取链接
3.获取statement对象

import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.IOException;import java.sql.Connection;import java.sql.DriverManager;import java.sql.SQLException;import java.sql.Statement;import java.util.Properties;public class ConnectionMySQL {    private Connection connection;    private Statement statement;    public ConnectionMySQL() {        String name = "root";        String password ="";        String url = "jdbc:mysql://localhost:3306/test";        String driver = "com.mysql.jdbc.Driver";        //加载驱动类到内存        try {            Class.forName(driver);        } catch (ClassNotFoundException e) {            e.printStackTrace();        }        try {            //获取链接            connection = DriverManager.getConnection(url, name, password);            //获取statement对象            statement = connection.createStatement();        } catch (SQLException e) {            e.printStackTrace();        }    }    public void colseMySQL() {        if (statement==null || connection==null || fis==null) {            return;        }        try {            statement.close();            connection.close();        } catch (SQLException e) {            e.printStackTrace();        }        try {            fis.close();        } catch (IOException e) {            e.printStackTrace();        }    }    public Statement getStatement() {        return statement;    }    @Override    protected void finalize() throws Throwable {        if (statement==null || connection==null || fis==null) {            return;        }        statement.close();        connection.close();        fis.close();    }}
原创粉丝点击