美文网首页The Magnificent JavaJava学习笔记
Java:jdbc连接数据库MariaDB/Mysql

Java:jdbc连接数据库MariaDB/Mysql

作者: HE1HE | 来源:发表于2016-05-17 09:17 被阅读5349次

    这里是用的Mysql的分支版本MariaDB,除了安装的包不同外,操作基本相同。
    本人用的是Archlinux,也只是安装软件的方式不同。

    一、MariaDB

    + [安装](https://wiki.archlinux.org/index.php/Pacman)位于[官方软件源](https://wiki.archlinux.org/index.php/Official_repositories)的[mariadb](https://www.archlinux.org/packages/?name=mariadb)、[libmariadbclient](https://www.archlinux.org/packages/?name=libmariadbclient) 和 [mariadb-clients](https://www.archlinux.org/packages/?name=mariadb-clients)
    + 运行: 
    
    # mysql_install_db --user=mysql --basedir=/usr --datadir=/var/lib/mysql
    
    + 启动 mysqld[守护进程](https://wiki.archlinux.org/index.php/Daemon),运行安装脚本,然后重新启动守护进程:(按提示设置MariaDB用户名和密码)
    
    # systemctl start mysqld
    # mysql_secure_installation
    # systemctl restart mysqld
    
    • 启动、登录,建立数据库
    • 启动:
    # systemctl start mysqld
    
    • 登录:(这里是用的root用户,可以把root换为自己的用户名)
    $ mysql -p -u root
    
    • 创建测试用的数据库(登录后)
    MariaDB [(none)]> create database test;
    

    二、eclipse建立测试项目

    用户名和密码设为自己的。

    package test;
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.SQLException;
    import java.util.Properties;
    public class MariaDB {
        // The JDBC Connector Class.
        private static final String dbClassName = "org.mariadb.jdbc.Driver";
        // Connection string. emotherearth is the database the program
        // is connecting to. You can include user and password after this
        // by adding (say) ?user=paulr&password=paulr. Not recommended!
        private static final String CONNECTION =
                              "jdbc:mariadb://localhost:3306/emotherearth";
        public static void main(String[] args) throws
                                 ClassNotFoundException,SQLException
        {
            System.out.println(dbClassName);
            // Class.forName(xxx) loads the jdbc classes and
            // creates a drivermanager class factory
            Class.forName(dbClassName);
            // Properties for user and password. Here the user and password are both 'paulr'
            Properties p = new Properties();
            p.put("user","root");
            p.put("password","123456");
            // Now try to connect
            Connection c = DriverManager.getConnection(CONNECTION,p);
            System.out.println("It works !");
            c.close();
        }
    }
    

    二、jdbc连接器

    方法一:

    方法二: 安装包 mariadb-jdbcAUR

    $ yaourt mariadb-jdbc
    

    要确保项目里有了Mariadb-Java-Client.jar

    三、运行测试

    此时运行测试程序,得到:

    org.mariadb.jdbc.Driver
    It works !
    

    相关文章

      网友评论

        本文标题:Java:jdbc连接数据库MariaDB/Mysql

        本文链接:https://www.haomeiwen.com/subject/rhxirttx.html