当前位置:首页 > PHP教程 > PHP总结归纳

java学习之联接Mysql

java 学习之连接 mysql 首先导入 mysql-connector-java-5.1.10-bin.ja 下载地址: http://download.csdn.net/detail/u014112584/7359185 鼠标放在项目上,右击选择properties-----java build path ------add external jars 测试代码: import java.sql.connec

java 学习之连接 mysql

首先导入mysql-connector-java-5.1.10-bin.ja

下载地址:http://download.csdn.net/detail/u014112584/7359185

鼠标放在项目上,右击选择properties----->java build path ------>add external jars

 

测试代码:

import java.sql.connection; import java.sql.drivermanager; import java.sql.resultset; import java.sql.sqlexception; import com.mysql.jdbc.preparedstatement; import com.mysql.jdbc.statement; public class mysqltest { static string drivername="com.mysql.jdbc.driver"; static string url="jdbc:mysql://localhost:3306/expression";//指向数据源 static string username="root"; static string password=""; static java.sql.statement stmt=null; static resultset re=null; static connection conn=null; static preparedstatement pstm=null; /* * 构造函数进行初始化 */ public mysqltest(){ try{ class.forname(drivername);//将驱动加载到运行环境中,加载的时候,驱动会自动向drivermanager完成注册 system.out.println("创建驱动成功"); }catch(classnotfoundexception e){ e.printstacktrace(); } } /* * 获取连接 */ public static connection getconnection(){ conn=null; try{ conn=(connection)drivermanager.getconnection(url, username, password);//有了驱动和连接地址后,需要使用drivermanager来获取连接 system.out.println("连接数据库成功!"); }catch(sqlexception e){ e.printstacktrace(); } return conn; } /** * 关闭连接 * @param args */ public static void free(resultset rs,connection conn,java.sql.statement stmt2){ if(rs!=null){ try { rs.close(); } catch (sqlexception e) { // todo auto-generated catch block system.out.println("关闭resultset失败!"); e.printstacktrace(); }finally{ if(conn!=null){ try { conn.close(); } catch (sqlexception e) { // todo auto-generated catch block system.out.println("关闭connection失败!"); e.printstacktrace(); }finally{ if(stmt2!=null){ try { stmt2.close(); } catch (sqlexception e) { // todo auto-generated catch block system.out.println("关闭statement失败!"); e.printstacktrace(); } } } } } } } public static void main(string[]args){ mysqltest.getconnection(); try { stmt=conn.createstatement(); } catch (sqlexception e) { // todo auto-generated catch block e.printstacktrace(); } try { re=stmt.executequery("select * from data"); } catch (sqlexception e) { // todo auto-generated catch block e.printstacktrace(); } int i=1; try { while(re.next()){ system.out.println(i++); } } catch (sqlexception e) { // todo auto-generated catch block e.printstacktrace(); } free(re,conn,stmt); system.out.println("ok"); } }
java 访问数据库更多例子http://download.csdn.net/detail/u014112584/735917.syntaxhighlighter{padding-top:20px;padding-bottom:20px;}

【说明】本文章由站长整理发布,文章内容不代表本站观点,如文中有侵权行为,请与本站客服联系(QQ:)!