java连接MySQL数据库的超强版

    xiaoxiao2025-10-11  7

    <pre name="code" class="java">import java.sql.*; public class jdbc { public static void main(String[] args){ ResultSet rs = null; Statement stmt = null; Connection conn = null; try{ String str = null; String url = null; //先将build path路径下的jar中的driver类new出实例,并且自动的向DriverManager注册信息 Class.forName("com.mysql.jdbc.Driver"); url = "jdbc:mysql://localhost:3306/fb"; //主机名-端口-数据库名,通过将url,用户名,密码传向DriverManager拿到connection(相当于委托DM打通关系) conn = DriverManager.getConnection(url, "root",""); //创建statement对象,(得到了关系通过正常的陈述方式和数据库联系起来,结果存放到结果集中) stmt = conn.createStatement(); rs = stmt.executeQuery("select * from stu"); while(rs.next()){ System.out.println(rs.getString("Sage")); } }catch(ClassNotFoundException e){//new对象时的异常 e.printStackTrace(); }catch(SQLException e){//getconnection、creatStatement异常 e.printStackTrace();//出错可以记录log4j文件中 }finally{ try{ if(rs != null ){ rs.close(); rs = null;//让垃圾回收器随时收回去 } if(stmt != null ){ stmt.close(); stmt = null; } if(conn != null ){ conn.close(); conn = null; } }catch(SQLException e){ e.printStackTrace(); } } } }
    转载请注明原文地址: https://ju.6miu.com/read-1303052.html
    最新回复(0)