想通过java编写一个创建数据库和数据库中表等其他对象的程序..........?
------解决方案--------------------
- Java code
import java.sql.*;public class Test{ public static void main(String[] args) throws Exception { Class.forName("com.mysql.jdbc.Driver"); //一开始必须填一个已经存在的数据库 String url = "jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8"; Connection conn = DriverManager.getConnection(url, "root", "123456"); Statement stat = conn.createStatement(); //创建数据库hello stat.executeUpdate("create database hello"); //打开创建的数据库 stat.close(); conn.close(); url = "jdbc:mysql://localhost:3306/hello?useUnicode=true&characterEncoding=utf-8"; conn = DriverManager.getConnection(url, "root", "123456"); stat = conn.createStatement(); //创建表test stat.executeUpdate("create table test(id int, name varchar(80))"); //添加数据 stat.executeUpdate("insert into test values(1, '张三')"); stat.executeUpdate("insert into test values(2, '李四')"); //查询数据 ResultSet result = stat.executeQuery("select * from test"); while (result.next()) { System.out.println(result.getInt("id") + " " + result.getString("name")); } //关闭数据库 result.close(); stat.close(); conn.close(); }}
------解决方案--------------------
创建数据库和数据库中表的sql会写不?
只要会写sql就行,java也只是调用这些创建的sql而已。。。
------解决方案--------------------
- Java code
public static void execute(String sql){ Connection conn = null; Statement st = null; try { Class.forName("com.mysql.jdbc.Driver"); conn = DriverManager.getConnection("jdbc:mysql://localhost/test", "root", "root"); st = conn.createStatement(); st.execute(sql); } catch(ClassNotFoundException e){ e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } finally{ try { if(conn!=null)conn.close(); if(st!=null)st.close(); } catch (SQLException e) { e.printStackTrace(); } } }
------解决方案--------------------
非主流需求,实际中没人动态去创建数据库的!