在这篇文章中,我们将向你展示如何创建和使用DataSource
对象,在不使用JNDI服务的情况下获得对数据源的连接。
从https://dev.mysql.com/downloads/connector/j/下载MySQL JDBC驱动,并添加到你项目的构建路径中。
下面的例子演示了如何从MySQL数据源中获得一个连接。同时,我们将使用Statement接口创建一个雇员表。
package com.javaguides.jdbc.statement.examples.packages;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import javax.sql.DataSource;
import com.mysql.jdbc.jdbc2.optional.MysqlDataSource;
/**
* JDBC MysqlDataSource Example
* @author Ramesh Fadatare
*
*/
public class DataSourceExample {
private static final String createTableSQL = "create table employee (\r\n" + " id int(3) primary key,\r\n" +
" name varchar(20),\r\n" + " email varchar(20),\r\n" + " country varchar(20),\r\n" +
" password varchar(20)\r\n" + " );";
private static DataSource getMySQLDatasource() {
MysqlDataSource dataSource = new MysqlDataSource();
// Set dataSource Properties
dataSource.setServerName("localhost");
dataSource.setPortNumber(3306);
dataSource.setDatabaseName("mysql_database");
dataSource.setUser("root");
dataSource.setPassword("root");
return dataSource;
}
public static void main(String[] argv) throws SQLException {
DataSourceExample dataSourceExample = new DataSourceExample();
dataSourceExample.createTable();
}
public void createTable() throws SQLException {
System.out.println(createTableSQL);
// Step 1: Establishing a Connection
try (Connection connection = getMySQLDatasource().getConnection();
// Step 2:Create a statement using connection object
Statement statement = connection.createStatement();) {
// Step 3: Execute the query or update query
statement.execute(createTableSQL);
} catch (SQLException e) {
// print SQL exception information
printSQLException(e);
}
// Step 4: try-with-resource statement will auto close the connection.
}
public static void printSQLException(SQLException ex) {
for (Throwable e: ex) {
if (e instanceof SQLException) {
// e.printStackTrace(System.err);
System.err.println("SQLState: " + ((SQLException) e).getSQLState());
System.err.println("Error Code: " + ((SQLException) e).getErrorCode());
System.err.println("Message: " + e.getMessage());
Throwable t = ex.getCause();
while (t != null) {
System.out.println("Cause: " + t);
t = t.getCause();
}
}
}
}
}
输出:
create table employee (
id int(3) primary key,
name varchar(20),
email varchar(20),
country varchar(20),
password varchar(20)
);
版权说明 : 本文为转载文章, 版权归原作者所有 版权申明
原文链接 : https://www.javaguides.net/2018/10/jdbc-datasource-connection-mysql-example.html
内容来源于网络,如有侵权,请联系作者删除!