JDBC连接MySQL5.7的方法
程序员文章站
2023-11-04 16:59:52
1.首先准备mysql 和eclipse环境,在环境搭建好之后,从eclipse官网下载jdbc的驱动包,下载地址
2.从下载的文件中取出mysql-connector-...
1.首先准备mysql 和eclipse环境,在环境搭建好之后,从eclipse官网下载jdbc的驱动包,下载地址
2.从下载的文件中取出mysql-connector-java-5.1.31-bin.jar,放到工程中,并导入路径
方法:右击工程名->build path->configure build path,选择add external jar... 找到mysql-connector-java-5.1.31-bin.jar所在的位置,然后将驱动包加载到项目中,
3.写个例子测试一下
package testmysql; import java.sql.*; public class test { public static void main(string[] args) { string driver = "com.mysql.jdbc.driver"; string url = "jdbc:mysql://localhost:3306/student"; connection con = null; try { class.forname(driver); } catch(java.lang.classnotfoundexception e) { system.out.println("connect successfull."); system.out.println("cant't load driver"); } try { con=drivermanager.getconnection(url,"root","root"); system.out.println("connect successfull."); } catch(exception e) { system.out.println("connect fail:" + e.getmessage()); } } }
连接上数据库之后,可以根据表中的内容进行数据库表的查询,首先表中要有内容,将一些信息输入到表中之后即可使用sql语言进行查询
import java.sql.*; public class main { public static void main(string[] args) { string driver = "com.mysql.jdbc.driver"; string url = "jdbc:mysql://localhost:3306/xiaolu"; connection con = null; resultset rs = null; statement st = null; string sql = "select * from student"; try { class.forname(driver); } catch(java.lang.classnotfoundexception e) { // system.out.println("connect successfull."); system.out.println("cant't load driver"); } try { con=drivermanager.getconnection(url,"root","root"); st=con.createstatement(); rs=st.executequery(sql); if(rs!=null) { resultsetmetadata rsmd = rs.getmetadata(); int countcols = rsmd.getcolumncount(); for(int i=1;i<=countcols;i++) { if(i>1) system.out.print(";"); system.out.print(rsmd.getcolumnname(i)+" "); } system.out.println(""); while(rs.next()) { system.out.print(rs.getstring("sno")+" "); system.out.print(rs.getstring("sname")+" "); system.out.print(rs.getstring("ssex")+" "); system.out.print(rs.getstring("sage")+" "); system.out.println(rs.getstring("sdept")+" "); } } //system.out.println("connect successfull."); system.out.println("ok"); rs.close(); st.close(); con.close(); } catch(exception e) { system.out.println("connect fail:" + e.getmessage()); } } }
关于jdbc连接mysql5.7的文章就介绍到这,其他的可以查下其它相关文章。