java创建数据库

在这之前一直都是先在Oracle、MySql等数据库中将数据库、表等操作创建好,再开始编写代码,最近看到一个项目则是通过java代码来执行sql语句来创建数据库这一系列的操作,感觉还是蛮新鲜的,起码对我来说是这样的,接下来将部分的关键代码记录下来,方便后面忘了再回来看看

这里面我用到了c3p0包中的ComboPooledDataSource类和spring中的JdbcTemplate类,在之前对这两个类不了解,这里也借这个机会学习学习这两个类

如果要使用这两个类必须导入c3p0-x.x.xjar好spring.jar包

使用ComboPooledDataSource获取数据源

public DataSource createDataSource(String driver, String url,
			String userName, String password) {
		try {
			//创建ComboPooledDataSource
			ComboPooledDataSource comboPooledDataSource=new ComboPooledDataSource();
			//设置相应参数
			comboPooledDataSource.setDriverClass(driver);
			comboPooledDataSource.setJdbcUrl(url);
			comboPooledDataSource.setUser(userName);
			comboPooledDataSource.setPassword(password);
			//设置最小连接个数
			comboPooledDataSource.setMinPoolSize(5);
			//设置最大连接个数
			comboPooledDataSource.setMaxPoolSize(50);
			//设置最大空闲时间
			comboPooledDataSource.setMaxIdleTime(5000);
			//返回数据源对象
			return comboPooledDataSource;
		} catch (PropertyVetoException e) {
			e.printStackTrace();
		}
		return null;
	}


 

 

测试MySql连接代码

/**
	 * 测试Mysql连接
	 * @return
	 */
	private boolean testMySqlConnection(){
		//数据库驱动
		String driverClass="com.microsoft.sqlserver.jdbc.SQLServerDriver";
		//数据库连接
		String conUrl="jdbc:mysql://"+this.url+"/test";
		try {
			//获取数据源对象
			DataSource newDataSource=dataScourceCreate.createDataSource(driverClass, conUrl, userName, password);
			//为jdbcTemplate设置数据源
			this.jdbcTemplate.setDataSource(newDataSource);
			//sql语句--创建数据库
			String sql="CREATE DATABASE IF NOT EXISTS "+this.name+" DEFAULT CHARACTER SET UTF8";
			//执行sql语句
			this.jdbcTemplate.execute(sql);
			//获取数据源--测试刚创建的数据库
			newDataSource=dataScourceCreate.createDataSource(driverClass, "jdbc:mysql://"+this.url+"/"+this.name+"", userName, password);
			this.jdbcTemplate.setDataSource(newDataSource);
			this.jdbcTemplate.execute("use "+this.name);
			this.jdbcTemplate.execute("create table if not exists student(id int not null)");
			this.jdbcTemplate.execute("drop table student");
			return true;
		} catch (DataAccessException e) {
			e.printStackTrace();
			return false;
		}
	}


测试SqlServer连接

/**
	 * 测试SqlServer数据库连接
	 * @return
	 */
	private boolean testSqlServerConnection(){
		//数据库驱动
		String driverClass="com.microsoft.sqlserver.jdbc.SQLServerDriver";
		//数据库连接
		String conUrl="jdbc:sqlserver://"+this.url+";databasename=master";
		try {
			//获取数据源对象
			DataSource newDataSource=dataScourceCreate.createDataSource(driverClass, conUrl, userName, password);
			//设置数据源
			this.jdbcTemplate.setDataSource(newDataSource);
			//创建是否存在数据库sql语句
			String sql="if exists(select 1 from sysdatabases where name='"+this.name+"') drop database "+this.name;
			//执行sql语句
			this.jdbcTemplate.execute(sql);
			//获取创建数据库sql语句并执行
			this.jdbcTemplate.execute(sqlUtil.createDataBaseSql(this.name));
			//从新获取数据源--测试刚创建的数据库
			newDataSource=dataScourceCreate.createDataSource(driverClass, "jdbc:sqlserver://"+this.url+";databasename="+this.name, userName, password);
			this.jdbcTemplate.setDataSource(newDataSource);
			this.jdbcTemplate.execute("use "+this.name);
			//执行判断表是否存在
			this.jdbcTemplate.execute("if exists(select 1 from sysobjects where name='test') drop table test");
			//创建表
			this.jdbcTemplate.execute("create table test(id int not null)");
			//删除表
			this.jdbcTemplate.execute("drop table test");
			return true;
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
	}


测试Oracle连接

/**
	 * 测试Oracle连接
	 * @return
	 */
	private boolean testOracleConnection(){
		//数据库驱动
		String driverClass="oracle.jdbc.driver.OracleDriver";
		//数据库连接
		String conUrl="jdbc:oracle:thin:@"+this.url+":orcl";
		try {
			//获取数据源对象
			DataSource newDataSource=dataScourceCreate.createDataSource(driverClass, conUrl, "system", password);
			//设置数据源
			this.jdbcTemplate.setDataSource(newDataSource);
			//查询需要创建的用户是否存在
			int result=jdbcTemplate.queryForInt("select count(*) from all_users where USERNAME='"+this.userName.toUpperCase()+"'");
			if(result>0){
				Map map=jdbcTemplate.queryForMap("select sid,serial# from v$session where upper(username)=upper('"+this.userName.toUpperCase()+"')");
				//执行关闭
				jdbcTemplate.execute("alter system kill session '"+map.get("SID")+","+map.get("SERIAL#")+"'");
				//删除用户
				jdbcTemplate.execute("DROP USER "+this.userName.toUpperCase()+" CASCADE");
			}
			//创建用户
			this.jdbcTemplate.execute("CREATE USER "+this.userName+" IDENTIFIED BY "+this.password);
			//给新建用户绑定权限
			this.jdbcTemplate.execute("GRANT CONNECT,RESOURCE TO "+this.userName);
			//连接新创建的用户
			newDataSource=dataScourceCreate.createDataSource(driverClass, conUrl, this.userName, this.password);
			//设置新用户的数据源
			this.jdbcTemplate.setDataSource(newDataSource);
			//查询该用户是否存在表
			result=jdbcTemplate.queryForInt("SELECT count(*) FROM USER_TAB_COMMENTS WHERE TABLE_NAME='TEST'");
			if(result>0){
				//删除表
				this.jdbcTemplate.execute("DROP TABLE TEST");
			}
			//创建表
			this.jdbcTemplate.execute("CREATE TABLE TEST(ID NUMBER NOT NULL)");
			//删除表
			this.jdbcTemplate.execute("DROP TABLE TEST");
			return true;
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
	}


关键代码都在这了,目前我只了解这3个数据库,所以也只有这3个了,代码没做优化,如果你们觉得有用,优化就自己弄吧

 

  • 3
    点赞
  • 23
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
Java可以通过JDBC API连接数据库,并通过执行SQL语句来创建数据库和表。以下是大致步骤: 1. 导入JDBC API相关的jar包,这些jar包包含了连接数据库所需的驱动程序。 2. 加载JDBC驱动程序,使用Class.forName()方法加载驱动程序。 3. 使用DriverManager.getConnection()方法连接数据库。 4. 创建Statement对象,用于执行SQL语句。 5. 执行SQL语句,可以通过execute()方法执行任何SQL语句,如创建数据库、创建表等。 6. 关闭连接,释放资源。 下面是一个示例代码,创建一个名为“mydb”的数据库,以及其中的一个名为“employees”的表: ``` import java.sql.Connection; import java.sql.DriverManager; import java.sql.Statement; public class CreateDBandTable { public static void main(String[] args) { String url = "jdbc:mysql://localhost:3306/"; String dbName = "mydb"; String driver = "com.mysql.jdbc.Driver"; String userName = "root"; String password = "root"; try { Class.forName(driver).newInstance(); Connection conn = DriverManager.getConnection(url + dbName, userName, password); Statement stmt = conn.createStatement(); //创建数据库 String createDB = "CREATE DATABASE mydb"; stmt.executeUpdate(createDB); //选择数据库 String useDB = "USE mydb"; stmt.executeUpdate(useDB); //创建表 String createTable = "CREATE TABLE employees " + "(id INT(11) NOT NULL AUTO_INCREMENT, " + " first_name VARCHAR(255), " + " last_name VARCHAR(255), " + " age INT(11), " + " PRIMARY KEY ( id ))"; stmt.executeUpdate(createTable); conn.close(); } catch (Exception e) { e.printStackTrace(); } } } ```
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小老虎Love

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值