mySQL数据库连接

来源:互联网 发布:photoshop有没有mac版 编辑:程序博客网 时间:2024/04/30 09:31
import java.sql.Connection;import java.sql.DriverManager;import java.sql.PreparedStatement;import java.sql.ResultSet;public class MysqlConnection {    private static MysqlConnection mySQLConnection = null;    private Connection connection;    private static final String DBDRIVER = "com.mysql.jdbc.Driver";//数据库驱动    private static final String DBURL = "jdbc:mysql://localhost:3306/test";//mysql的URL;    private static final String DBUSERNAME = "root";//数据库登录的用户名    private static final String DBPASSWORD = "root";//数据库登录密码    public MysqlConnection() {        try {            Class.forName(DBDRIVER);//加载数据库的驱动        } catch (Exception e) {            e.printStackTrace();        }    }    public static MysqlConnection Driver() {        if (mySQLConnection == null) {            mySQLConnection = new MysqlConnection();        }        return mySQLConnection;    }    public Connection getConnection() {        try {            connection = DriverManager.getConnection(DBURL, DBUSERNAME, DBPASSWORD);//建立数据库连接        } catch (Exception e) {            e.printStackTrace();        }        return connection;    }//逐一关闭开启的连接,Connection、PreparedStatement、ResultSet在后面的sql中会使用到,在此一并设置关闭    public static void close(Connection connection, PreparedStatement pstmt, ResultSet rs) {        try {            if (connection != null) {                connection.close();            }        } catch (Exception e) {            e.printStackTrace();        }        try {            if (pstmt != null) {                pstmt.close();            }        } catch (Exception e) {            e.printStackTrace();        }        try {            if (rs != null) {                rs.close();            }        } catch (Exception e) {            e.printStackTrace();        }    }}

要建立数据库的连接,首先就是导包:mysql-connector-*.jar,将jar包导入lib文件夹中然后built path。这个jar包不需要下载,可以在mysql安装文件中找到,搜索一下mysql-connectors就能找到。
接下来就是开始建立数据库的连接,总共分三步:加载驱动、建立连接、关闭连接。
加载驱动的固定格式

    Class.forName("com.mysql.jdbc.Driver");

驱动可以在library中的mysql-connector.jar包中的
/META-INF/services/java.sql.Driver
文件找到,前提是要built path才会在library中出现这个jar包。

MySQLURL的格式为:
jdbc:mysql://【服务器名】:【MySQL的端口号,默认是3306】/【数据库名】

jdbc:mysql://localhost:3306/test

建立数据库连接:

DriverManager.getConnection(DBURL, DBUSERNAME, DBPASSWORD);

关闭数据库的连接中,为了保证连接能够完全关闭,需要逐一关闭各个连接。如果在一起关闭连接,可能会因为某个连接关闭异常导致其他连接无法关闭。所以最好分开来关闭每个连接。
需要注意的是:加载驱动和关闭连接使用的是静态的方法,这样做可以避免直接新建对象来调用对应的方法。
最后的调用如下:

//连接MySQL数据库MysqlConnection.Driver().getConnection();//关闭连接MysqlConnection.close();
0 0
原创粉丝点击