java 学习之连接 mysql 首先要将 mysql-connector-java-5.1.10-bin.ja加入系统java工程文件中 下载地址http://download.csdn.net/detail/u014112584/7359185 Mysql-----右击选择Properties属性---------------Add External JARS 测试例子 import java.sql.Con
java 学习之连接 mysql首先要将mysql-connector-java-5.1.10-bin.ja加入系统java工程文件中
下载地址http://download.csdn.net/detail/u014112584/7359185
Mysql----->右击选择Properties属性--------------->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"); } }
http://download.csdn.net/detail/u014112584/7359179
已抢65249个
抢已抢29172个
抢已抢15908个
抢已抢7974个
抢已抢10192个
抢已抢20127个
抢