本文整理汇总了Java中java.sql.DriverManager类的典型用法代码示例。如果您正苦于以下问题:Java DriverManager类的具体用法?Java DriverManager怎么用?Java DriverManager使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
DriverManager类属于java.sql包,在下文中一共展示了DriverManager类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: getConnection
import java.sql.DriverManager; //导入依赖的package包/类
public static Connection getConnection() {
try {
DriverManager.registerDriver(new com.mysql.cj.jdbc.Driver());
String url = "jdbc:mysql://" + //db type
"localhost:" + //host name
"3306/" + //port
"db_example?" + //db name
"useSSL=false&" + //do not use ssl
"user=tully&" + //login
"password=tully"; //password
return DriverManager.getConnection(url);
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
示例2: register_user
import java.sql.DriverManager; //导入依赖的package包/类
public boolean register_user(String username,String pwd,String f_name,String l_name,String role)
{
try{
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/icms_employees?autoReconnect=true&useSSL=false","root","admin");
Statement st = con.createStatement();
st.executeUpdate("insert into `employees`(`first_name`,`last_name`,`username`,`password`,`role`) VALUES('"+f_name+"','"+l_name+"','"+username+"','"+pwd+"','"+role+"')");
registration_success=true;
st.close();
con.close();
} catch(Exception e) {
System.out.println(e.getMessage());
}
return registration_success;
}
示例3: getSQLiteConnection
import java.sql.DriverManager; //导入依赖的package包/类
/**
* Gets the {@link Connection} to the database
*
* @return the {@link Connection}
*/
public Connection getSQLiteConnection() {
if (isConnected()) {
return CONNECTIONS.get(this.getDatabasePath());
} else {
try {
closeSQLiteConnection();
Class.forName("org.sqlite.JDBC");
Connection c = DriverManager.getConnection(
"jdbc:sqlite:" + this.getDatabasePath());
CONNECTIONS.put(this.getDatabasePath(), c);
return c;
} catch (SQLException | ClassNotFoundException ignore) {
Bukkit.getLogger().log(Level.WARNING, "Failed to reconnect to " + this.getDatabasePath() + "! Check your sqllite.json inside AlphaLibary");
return null;
}
}
}
示例4: executeScript
import java.sql.DriverManager; //导入依赖的package包/类
public void executeScript() throws Exception {
Connection connection = null;
try {
Class.forName(driver);
connection = DriverManager.getConnection(url, userid, password);
Statement statement = connection.createStatement();
BufferedReader br = new BufferedReader(new InputStreamReader(sourceFile));
String sql;
while ((sql = readStatement(br)) != null) {
statement.execute(sql);
}
closeStatement(statement);
connection.commit();
br.close();
} finally {
closeConnection(connection);
}
}
示例5: doRegisterDriver
import java.sql.DriverManager; //导入依赖的package包/类
/**
* do register driver
*
* @param dr
*/
public Driver doRegisterDriver(Driver dr, boolean needRegisterToDriverManager) {
try {
if (needRegisterToDriverManager == true) {
DriverManager.deregisterDriver(dr);
}
Driver drProxy = JDKProxyInvokeUtil.newProxyInstance(this.getClass().getClassLoader(),
new Class<?>[] { Driver.class }, new JDKProxyInvokeHandler<Driver>(dr, new DriverProxy()));
if (needRegisterToDriverManager == true) {
DriverManager.registerDriver(drProxy);
}
return drProxy;
}
catch (SQLException e) {
logger.error("Install JDBC Driver Proxy FAIL.", e);
}
return dr;
}
示例6: testSchemaForEmptyResultSet
import java.sql.DriverManager; //导入依赖的package包/类
@Test
public void testSchemaForEmptyResultSet() throws Exception {
String query = "select fullname, occupation, postal_code from cp.`customer.json` where 0 = 1";
try (Connection c = DriverManager.getConnection("jdbc:drill:zk=local", null);) {
Statement s = c.createStatement();
ResultSet r = s.executeQuery(query);
ResultSetMetaData md = r.getMetaData();
List<String> columns = Lists.newArrayList();
for (int i = 1; i <= md.getColumnCount(); i++) {
System.out.print(md.getColumnName(i));
System.out.print('\t');
columns.add(md.getColumnName(i));
}
String[] expected = {"fullname", "occupation", "postal_code"};
Assert.assertEquals(3, md.getColumnCount());
Assert.assertArrayEquals(expected, columns.toArray());
// TODO: Purge nextUntilEnd(...) and calls when remaining fragment race
// conditions are fixed (not just DRILL-2245 fixes).
nextUntilEnd(r);
}
}
示例7: getConnection
import java.sql.DriverManager; //导入依赖的package包/类
/**
* 根据配置获取获取关系型数据库的jdbc连接
*
* @param conf
* hadoop配置信息
* @param flag
* 区分不同数据源的标志位
* @return
* @throws SQLException
*/
public static Connection getConnection(Configuration conf, String flag) throws SQLException {
String driverStr = String.format(GlobalConstants.JDBC_DRIVER, flag);
String urlStr = String.format(GlobalConstants.JDBC_URL, flag);
String usernameStr = String.format(GlobalConstants.JDBC_USERNAME, flag);
String passwordStr = String.format(GlobalConstants.JDBC_PASSWORD, flag);
String driverClass = conf.get(driverStr);
// String url = conf.get(urlStr);
String url = "jdbc:mysql://hadoop1:3306/result_db?useUnicode=true&characterEncoding=utf8";
// String username = conf.get(usernameStr);
// String password = conf.get(passwordStr);
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
// nothing
}
return DriverManager.getConnection(url, "root", "root");
}
示例8: StudentCourseOutlineDAO
import java.sql.DriverManager; //导入依赖的package包/类
public StudentCourseOutlineDAO(Student student)throws Exception{
Properties properties = new Properties();
properties.load(StudentCourseOutlineDAO.class.getResourceAsStream("/details.properties"));
String dbname=properties.getProperty("dbName");
String user=properties.getProperty("user");
String password=properties.getProperty("password");
try{System.out.println("StudentCourseOutlineDAO");
myCon=DriverManager.getConnection(dbname, user, password);
/*
* For Debugging Purpose
*/
//System.out.println("Connection Established");
}catch(SQLException exc){
System.out.println("Connection Problem::: Message ::");
exc.printStackTrace();
}
this.student = student;
if(student == null){
System.exit(0);
}
}
示例9: testDatabase
import java.sql.DriverManager; //导入依赖的package包/类
public void testDatabase(String driver, String connectionUrl, String username, String password, String dbtype,
String database) throws SQLException, ClassNotFoundException, NonUnicodeEncodingException
{
Connection connection = null;
try
{
// We USED to use Hibernate but I removed it due to ClassLoader
// issues. So shoot me...
Class.forName(driver);
connection = DriverManager.getConnection(connectionUrl, username, password);
DatabaseCommand.ensureUnicodeEncoding(connection, dbtype, database);
}
catch( SQLException pain )
{
throw new RuntimeException("Attempted connect at connectionURL (" + connectionUrl + "), username ("
+ username + "), password(" + password + "), dbtype(" + dbtype + "), database(" + database + ')', pain);
}
finally
{
if( connection != null )
{
connection.close();
}
}
}
示例10: testOpenConnectionWithProperties
import java.sql.DriverManager; //导入依赖的package包/类
@Test public void testOpenConnectionWithProperties() throws Exception {
// This tests that username and password are used for creating a connection on the
// server. If this was not the case, it would succeed.
try {
DriverManager.getConnection(url, "john", "doe");
fail("expected exception");
} catch (RuntimeException e) {
assertEquals("Remote driver error: RuntimeException: "
+ "java.sql.SQLInvalidAuthorizationSpecException: invalid authorization specification"
+ " - not found: john"
+ " -> SQLInvalidAuthorizationSpecException: invalid authorization specification - "
+ "not found: john"
+ " -> HsqlException: invalid authorization specification - not found: john",
e.getMessage());
}
}
示例11: testRemoteStatementInsert
import java.sql.DriverManager; //导入依赖的package包/类
@Test public void testRemoteStatementInsert() throws Exception {
ConnectionSpec.getDatabaseLock().lock();
try {
final String t = AvaticaUtils.unique("TEST_TABLE2");
AvaticaConnection conn = (AvaticaConnection) DriverManager.getConnection(url);
Statement statement = conn.createStatement();
final String create =
String.format(Locale.ROOT, "create table if not exists %s ("
+ " id int not null, msg varchar(255) not null)", t);
int status = statement.executeUpdate(create);
assertEquals(status, 0);
statement = conn.createStatement();
final String update =
String.format(Locale.ROOT, "insert into %s values ('%d', '%s')",
t, RANDOM.nextInt(Integer.MAX_VALUE), UUID.randomUUID());
status = statement.executeUpdate(update);
assertEquals(status, 1);
} finally {
ConnectionSpec.getDatabaseLock().unlock();
}
}
示例12: executeSqlScript
import java.sql.DriverManager; //导入依赖的package包/类
static void executeSqlScript(String server,
String db,
String schemaFile) {
ConsoleUtils.writeInfo("Executing script %s", schemaFile);
try (Connection conn = DriverManager.getConnection(Configuration.getConnectionString(server, db))) {
try (Statement stmt = conn.createStatement()) {
// Read the commands from the sql script file
ArrayList<String> commands = readSqlScript(schemaFile);
for (String cmd : commands) {
stmt.execute(cmd);
}
}
}
catch (SQLException e) {
e.printStackTrace();
}
}
示例13: shardMapManagerTestsCleanup
import java.sql.DriverManager; //导入依赖的package包/类
/**
* Cleans up common state for the all tests in this class.
*/
@AfterClass
public static void shardMapManagerTestsCleanup() throws SQLException {
Connection conn = null;
try {
conn = DriverManager.getConnection(Globals.SHARD_MAP_MANAGER_TEST_CONN_STRING);
// Create ShardMapManager database
try (Statement stmt = conn.createStatement()) {
String query = String.format(Globals.DROP_DATABASE_QUERY, Globals.SHARD_MAP_MANAGER_DATABASE_NAME);
stmt.executeUpdate(query);
}
catch (SQLException ex) {
ex.printStackTrace();
}
}
catch (Exception e) {
System.out.printf("Failed to connect to SQL database with connection string: " + e.getMessage());
}
finally {
if (conn != null && !conn.isClosed()) {
conn.close();
}
}
}
示例14: connect
import java.sql.DriverManager; //导入依赖的package包/类
@Override
public Connection connect() {
if (handler.isConnected()) {
return SQLConnectionHandler.getConnectionMap().get(handler.getInformation().getDatabaseName());
} else {
try {
handler.disconnect();
Connection c = DriverManager.getConnection(
"jdbc:mysql://" + handler.getInformation().getHost() + ":" + handler.getInformation().getPort() + "/" + handler.getInformation().getDatabaseName() + "?autoReconnect=true", handler.getInformation().getUserName(), handler.getInformation().getPassword());
SQLConnectionHandler.getConnectionMap().put(handler.getInformation().getDatabaseName(), c);
return c;
} catch (SQLException ignore) {
Bukkit.getLogger().log(Level.WARNING, "Failed to connect to " + handler.getInformation().getDatabaseName() + "! Check your mysql.yml inside the folder of " + handler.getPlugin().getName());
return null;
}
}
}
示例15: setUp
import java.sql.DriverManager; //导入依赖的package包/类
protected void setUp() throws Exception {
super.setUp();
user = "sa";
password = "";
stmnt = null;
connection = null;
TestUtil.deleteDatabase("/hsql/test/testpersistent");
try {
Class.forName("org.hsqldb.jdbc.JDBCDriver");
connection = DriverManager.getConnection(url, user, password);
stmnt = connection.createStatement();
} catch (Exception e) {
e.printStackTrace();
System.out.println("TestSqlPersistence.setUp() error: "
+ e.getMessage());
}
}