开发程序肯定离不开数据库,使用过Java的tx都知道,是通过JDBC来连接数据库。JDBC是什么呢?JDBC(JavaDataBaseConnectivity),是一套面向对象的应用程序接口(API),制定了统一的访问各种关系数据库的标准接口,只要各个数据库厂商实现了JDBC接口,Java程序就可以与这些数据库进行交互。本文就讲述了如何使用Java程序连接MySQL数据库
工具/原料
IntelliJIDEA
MySQL
方法/步骤
1、JDBC是一种底层API,在访问数据库是需要在业务逻辑中直接嵌入SQL语句。JDBC不能够直接访问数据库,必须依赖数据库厂商提供的JDBC驱动程序来实现Java程序与MySql的交互。http://dev.mysql.com/downloads/connector/点击“Connector/J”链接
2、在打开的页面,点PlatformIndependent(ArchitectureIndependent),ZIPArchive(mysql-connector-java-5.1.38.zip)后面的“download”链接Tips:当然下载“PlatformIndependent(ArchitectureIndependent),CompressedTARArchiv”(mysql-connector-java-5.1.38.tar.gz)也可以
3、在打开的页面,点击下面的“Nothanks,juststartmydownload.”链接http://120.52.72.59/cdn.mysql.com/c3pr90ntcsf0//Downloads/Connector-J/mysql-connector-java-5.1.38.zipTips:当然,注册一个帐户,然后再下载也可以
4、解压缩下载的mysql-connector-java-5.1.38.zip找到我们需要的mysql-connector-java-5.1.38-bin.jar
5、把mysql-connector-java-5.1.38-bin.jar添加到Project的依赖中
6、万事俱备,只剩下老揉孟阼写代码Code:packagejdbc;importjava.sql.*;/***Creat髫潋啜缅edbyMyWorldon2016/4/4.*/publicclassJDBCForMysql{publicstaticvoidmain(String[]args){Connectionconn=null;Statementstatement=null;ResultSetresultSet=null;try{Class.forName("com.mysql.jdbc.Driver");Stringurl="jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF8";conn=DriverManager.getConnection(url,"mysql","mysql");System.out.println("Connectionstatus,isClosed:"+conn.isClosed());statement=conn.createStatement();statement.executeUpdate("CREATETABLEIFNOTEXISTSstaff(idvarchar(20),namevarchar(20),lastModifiedTimedatetime)");for(inti=0;i<10;i++){Stringsql=String.format("insertintostaff(id,name,lastModifiedTime)values('%s','%s',current_timestamp())","no"+i,"name"+i);statement.addBatch(sql);}statement.executeBatch();resultSet=statement.executeQuery("selectid,name,lastModifiedTimefromstaff");ResultSetMetaDatametaData=resultSet.getMetaData();intcolumnCount=metaData.getColumnCount();for(inti=1;i<=columnCount;i++){System.out.print(metaData.getColumnLabel(i)+"\t");}System.out.println("");while(resultSet.next()){for(inti=1;i<=columnCount;i++){System.out.print(resultSet.getString(i)+"\t");}System.out.println("");}}catch(ClassNotFoundExceptione){e.printStackTrace();}catch(SQLExceptione){e.printStackTrace();}finally{if(resultSet!=null){try{resultSet.close();}catch(SQLExceptionignored){}}if(statement!=null){try{statement.close();}catch(SQLExceptionignored){}}if(conn!=null){try{conn.close();}catch(SQLExceptionignored){}}}}}
7、执行下看看结果:Output:Connectionstatus,isClos娣定撰钠ed:falseid na罪焐芡拂me lastModifiedTime no0 name0 2016-04-0416:47:02.0 no1 name1 2016-04-0416:47:03.0 no2 name2 2016-04-0416:47:03.0 no3 name3 2016-04-0416:47:03.0 no4 name4 2016-04-0416:47:03.0 no5 name5 2016-04-0416:47:03.0 no6 name6 2016-04-0416:47:04.0 no7 name7 2016-04-0416:47:04.0 no8 name8 2016-04-0416:47:04.0 no9 name9 2016-04-0416:47:04.0