JDBC for MySql5.5 简单示例
package com.anllin.mysqltest; import java.sql.*; public class MysqlTest { public static void main(String[] args) { connetMysqlTest(); } public static void connetMysqlTest() { String connectionUrl = "jdbc:mysql://localhost:3306/mydata?user=root&password=123" ; Connection conn = null ; Statement stmt = null ; ResultSet rs = null ; try { Class.forName( "com.mysql.jdbc.Driver" ); conn = DriverManager.getConnection(connectionUrl); conn.setAutoCommit( false ); stmt = conn.createStatement(); rs = stmt.executeQuery( "select * from dept" ); conn.commit(); System.out.print( "deptno" + " " ); System.out.print( "dname" + " " ); System.out.println( "loc" ); while (rs.next()) { System.out.print(rs.getInt( "deptno" ) + " " ); System.out.print(rs.getString( "dname" ) + " " ); System.out.println(rs.getString( "loc" )); } } catch (Exception e) { if ( null != conn) { try { conn.rollback(); } catch (SQLException e1) { e1.printStackTrace(); } } e.printStackTrace(); } finally { if ( null != rs) { try { rs.close(); rs = null ; } catch (Exception e2) { e2.printStackTrace(); } } if ( null != stmt) { try { stmt.close(); stmt = null ; } catch (Exception e2) { e2.printStackTrace(); } } if ( null != conn) { try { conn.close(); conn = null ; } catch (Exception e2) { e2.printStackTrace(); } } } } } |
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步