JDBC for MySql5.5 简单示例

本文提供了一个使用 Java 连接 MySQL 数据库并查询 dept 表数据的示例程序。该程序通过 JDBC 驱动连接本地 MySQL 数据库,执行 SQL 查询语句,并将查询结果打印到控制台。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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();
                 }
             }
         }
     }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值