Heim >Datenbank >MySQL-Tutorial >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"); } }