JDBC 连接 MariaDB 步骤原理及依赖包

本文详细介绍了如何使用JDBC连接MariaDB,包括获取和安装driver、配置classpath、使用Driver Manager和Driver Class,以及创建连接字符串。同时,还提供了一个创建表的示例代码,并提到了对SLF4J的日志依赖。
摘要由CSDN通过智能技术生成

获取driver(Obtaining the driver)

The driver (jar and source code)) can be downloaded from

https://downloads.mariadb.org/client-java/

安装(Installing the driver)

Installation is as simple as placing the .jar file in your classpath.

把.jar文件复制到程序的classpath下

如果是在Eclipse中做工程,则参照<使用Eclipse时导入第三方jar包之常用方法>
http://jingyan.baidu.com/article/6079ad0e7e4de128fe86db40.html

Requirements

  • Java 7 (until April 2015) or 8
  • com.sun.JNA is used by some library functions and a jar is available at

 https://github.com/twall/jna

  • only needed when connecting to the server with unix sockets or windows shared memory

 

  • A MariaDB or MySQL Server
  • maven (only if you want build from source)

Installing the driver

Installation of the client library is very simple, the jar file should be saved in an appropriate place for your application and the classpath of your application altered to include the MariaDB Client Library for Java Applications rather than your current connector.

Using the driver

The following subsections show the formatting of JDBC connection strings for MariaDB, MySQL database servers. Additionally, sample code is provided that demonstrates how to connect to one of these servers and create a table.

Driver Manager

Applications designed to use the driver manager to locate the entry point need no further configuration, the MariaDB Client Library for Java Applications will automatically be loaded and used in the way any previous MySQL driver would have been.

Driver Class

Please note that the driver class provided by the MariaDB Client Library for Java Applications is not com.mysql.jdbc.Driver butorg.mariadb.jdbc.Driver!

注意MariaDB 提供的驱动类已经不再是com.mysql.jdbc.Driver 而是org.mariadb.jdbc.Driver了

 

Connection strings

Format of the JDBC connection string is

JDBC连接字符串:

jdbc:mysql://<host>:<port>/<database>?<key1>=<value1>&<key2>=<value2>...

Altenatively

也可以用:

jdbc:mariadb://<host>:<port>/<database>?<key1>=<value1>&<key2>=<value2>...

can also be used.

 

Optional URL parameters

General remark: Unknown options accepted and are silently ignored.

Following options are currently supported.

keydescriptionsupported since version
userDatabase user name1.0.0
passwordPassword of database user1.0.0
fastConnectIf set, skips check for sql_mode, assumes NO_BACKSLASH_ESCAPES is *not* set1.0.0
useFractionalSecondsCorrectly handle subsecond precision in timestamps (feature available withMariaDB 5.3 and later).May confuse 3rd party components (Hibernated)1.0.0
allowMultiQueriesAllows multiple statements in single executeQuery1.0.0
dumpQueriesOnExceptionIf set to 'true', exception thrown during query execution contain query string1.1.0
useCompressionallow compression in MySQL Protocol1.0.0
useSSLForce SSL on connection1.1.0
trustServerCertificateWhen using SSL, do not check server's certificate1.1.1
serverSslCertServer's certificatem in DER form, or server's CA certificate. Can be used in one of 3 forms, sslServerCert=/path/to/cert.pem (full path to certificate), sslServerCert=classpath:relative/cert.pem (relative to current classpath), or as verbatim DER-encoded certificate string "------BEGING CERTIFICATE-----"1.1.3
socketFactoryto use custom socket factory, set it to full name of the class that implements javax.net.SocketFactory1.0.0
tcpNoDelaySets corresponding option on the connection socket1.0.0
tcpKeepAliveSets corresponding option on the connection socket1.0.0
tcpAbortiveCloseSets corresponding option on the connection socket1.1.1
tcpRcvBufset buffer size for TCP buffer (SO_RCVBUF)1.0.0
tcpSndBufset buffer size for TCP buffer (SO_SNDBUF)1.0.0
pipeOn Windows, specify named pipe name to connect to mysqld.exe1.1.3
tinyInt1isBitDatatype mapping flag, handle MySQL Tiny as BIT(boolean)1.0.0
yearIsDateTypeYear is date type, rather than numerical1.0.0
sessionVariables<var>=<value> pairs separated by comma, mysql session variables, set upon establishing successfull connection1.1.0
localSocketAllows to connect to database via Unix domain socket, if server allows it. The value is the path of Unix domain socket, i.e "socket" database parameter1.1.4
sharedMemoryAllowed to connect database via shared memory, if server allows it. The value is base name of the shared memory1.1.4

 

 

JDBC API Implementation Notes

Streaming result sets

By default, Statement.executeQuery() will read full result set from server before returning. With large result sets, this will require large amounts of memory. Better behavior in this case would be reading row-by-row, with ResultSet.next(), so called "streaming" feature. It is activated using Statement.setFetchSize(Integer.MIN_VALUE)

Prepared statements

The driver only uses text protocol to communicate with the database. Prepared statements (parameter substitution) is handled by the driver, on the client side.

CallableStatement

Callable statement implementation won't need to access stored procedure metadata (mysql.proc) table if both of following are true

  • CallableStatement.getMetadata() is not used
  • Parameters are accessed by index, not by name

When possible, following the two rules above provides both better speed and eliminates concerns about SELECT privileges on the mysql.proc table.

Optional JDBC classes

Following optional interfaces are implemented by the org.mariadb.jdbc.MySQLDataSource class : javax.sql.DataSource, javax.sql.ConnectionPoolDataSource, javax.sql.XADataSource

Usage examples

The following code provides a basic example of how to connect to a MariaDB or MySQL server and create a table.

 

Creating a table on a MariaDB or MySQL Server

Connection  connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "username", "password");
Statement stmt = connection.createStatement();
stmt.executeUpdate("CREATE TABLE a (id int not null primary key, value varchar(20))");
stmt.close();
connection.close();

 

关于mariadb对SLF4J的依赖

经测mariadb-java-client-1.2.2.jar需要SLF4J的支持. 如果没有导入SLF4J 的jar包, 连接数据库时会报如下错误:

java.lang.NoClassDefFoundError: org/slf4j/LoggerFactory
 at org.mariadb.jdbc.Driver.<clinit>

Caused by: java.lang.ClassNotFoundException: org.slf4j.LoggerFactory

 

导入SLF4J核心包(slf4j-api-1.7.12.jar)后, 程序可以正常运行, 但仍会报一个警告:

SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".

导入slf4j-jdk14-1.7.12.jar包后修复.

 

附SLF4J下载地址:http://www.slf4j.org/download.html

您好!要使用JDBC连接MariaDB数据库,您需要遵循以下步骤: 1. 首先,确保您已经安装了MariaDB数据库,并且数据库服务器正在运行。 2. 在您的Java项目中,添加MariaDB JDBC驱动的依赖。您可以在Maven或Gradle等构建工具中添加以下依赖项: Maven: ```xml <dependency> <groupId>org.mariadb.jdbc</groupId> <artifactId>mariadb-java-client</artifactId> <version>2.7.2</version> </dependency> ``` Gradle: ``` implementation 'org.mariadb.jdbc:mariadb-java-client:2.7.2' ``` 3. 在您的Java代码中,导入必要的类: ```java import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; ``` 4. 在您的代码中,使用以下代码片段创建数据库连接: ```java public class Main { public static void main(String[] args) { String url = "jdbc:mariadb://localhost:3306/your_database_name"; String username = "your_username"; String password = "your_password"; try { Connection conn = DriverManager.getConnection(url, username, password); // 连接成功,可以执行数据库操作 // ... conn.close(); // 关闭连接 } catch (SQLException e) { e.printStackTrace(); } } } ``` 请将 `your_database_name` 替换为您要连接数据库名称,`your_username` 替换为数据库用户名,`your_password` 替换为数据库密码。 5. 运行代码,如果一切正常,您应该成功连接MariaDB数据库。 希望这可以帮助到您!如果您有其他问题,请随时提问。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值