直接在myeclipse里写代码新建数据库

 时间:2024-09-20 18:27:18

直接在myeclipse里写代码新建数据库

工具/原料

myeclipse

MySQL

方法/步骤

1、在需要新建数据库的Java项目里新建一个类文件(*.java),笔者是命名为MakeSql.java。开始写代码:

2、packagetest;impo筠续师诈rtjava.sql.*;publicclassMakeSql{ publicMakeSq造婷用痃l(){ Stringdatabase="newsql";//需要用的数据库名 getConn(database);//自定义的方法 } publicvoidgetConn(Stringdatabase){ //定义MySQL的数据库驱动程序 StringmysqlDriver="com.mysql.jdbc.Driver"; //MySQL数据库的连接用户名 Stringusername="root"; //MySQL数据库的连接密码 Stringpassword="123123"; try{ //加载驱动程序 Class.forName(mysqlDriver); }catch(ClassNotFoundExceptione){ e.printStackTrace(); } try{ //要新建数据库时,需要连接已有的数据库,而mysql是安装MySQL后的就存在数据库 //定义MySQL数据库的连接地址 Stringurl="jdbc:mysql://127.0.0.1:3306/mysql" +"?useUnicode=true&characterEncoding=utf-8&useSSL=false"; //数据库连接 Connectionconn=null; //连接到mysql这个数据库 conn=DriverManager.getConnection(url,username,password);

直接在myeclipse里写代码新建数据库

3、 //实例化S隋茚粟胫tatement对象 Statementsmt=conn.createStatement(); if(艘早祓胂conn!=null){//如果连接成功 //MySQL数据库语句——作用:创建新的数据库,并设置varchar的字符集为utf8,使得中文可正常显示 StringdatabaseSql1="createdatabase"+database+"charactersetutf8;"; //执行操作,创建所需的数据库 smt.executeUpdate(databaseSql1); //定义新的MySQL数据库的连接地址 StringnewUrl="jdbc:mysql://127.0.0.1:3306/"+database +"?useUnicode=true&characterEncoding=utf-8&useSSL=false"; //新的数据库连接 ConnectionnewConn=null; //创建了新的数据库后,连接到这个数据库 newConn=DriverManager.getConnection(newUrl,username,password); if(newConn!=null){ //连接到新建的数据库 StatementnewSmt=newConn.createStatement(); //MySQL数据库语句——作用:新建数据库后,转到使用该新建的数据库 StringdatabaseSql2="use"+database; inti=newSmt.executeUpdate(databaseSql2);//执行成功时,返回值为0; //MySQL数据库语句——作用:创建user的表,表头的内容有: //序号(num),ID(id),密码(password),名字(name) StringtableSql1="createtableuser(" +"numint(5)notnullprimarykeyauto_increment," +"idint(5)notnull," +"passwordvarchar(20)notnull," +"namevarchar(20)notnull);"; into=newSmt.executeUpdate(tableSql1);//执行成功时,返回值为0; //MySQL数据库语句——作用:创建表后,在这个表里创建一个初始的账号(123),密码(123),名字(123) StringtableSql2="INSERTINTOuser(id,password,name)"+"values(123,123,123);"; intp=newSmt.executeUpdate(tableSql2);//执行成功时,返回值为0;

直接在myeclipse里写代码新建数据库

4、 if(i!=0||o!=0||p!=0){//用来判断所需的数据库的表、表头、初始信息 //是否创建成功 System.out.println("创建数据库"+database+"成功!"); }else{ System.out.println("创建数据库"+database+"失败!"); } } } }catch(SQLExceptione1){ e1.printStackTrace(); } } publicstaticvoidmain(String[]args){//开始新建数据库 newMakeSql(); }}

直接在myeclipse里写代码新建数据库

5、代码写完后,运行。控制台显示了语句,此时数据库创建成功。

直接在myeclipse里写代码新建数据库

6、更进一步的查看数据库是否创建成功,笔者推荐用NavicatforMySQL这个软件。当然这个软件也可以用来创建、修改数据库,只是笔者用来查看罢了,其他功能的使用方法,请自行百度。

直接在myeclipse里写代码新建数据库

powerdesigner创建应用架构图 如何关闭MyEclipse应用中servers窗口下的tomcat 如何设置Java窗体的图标 thinkphp如何在html页面输出数据库数据 Eclipse高亮显示当前(光标处的)变量
热门搜索
漫画party 门神图片 jj图片 成人漫画 乌拉草图片