Eclipse JDBC MySQL

本文通过一个具体的Java程序示例,展示了如何使用JDBC进行数据库的基本操作,包括连接数据库、执行SQL语句、插入和删除数据以及处理结果集。
import java.sql.*;

public class JDBCHelloWorld
{
    public static void main(String[] args)
    {    // 1. 注册驱动
        try {
            Class.forName("com.mysql.jdbc.Driver");
            }
        catch (ClassNotFoundException e) {
            e.printStackTrace();
            }// Mysql 的驱动
            // 先定义变量,后使用和关闭
            Connection conn = null;// 数据库连接
            Statement stmt = null;// 数据库表达式 ResultSet rs = null;// 结果集
            ResultSet rs = null;
            try {
                // 2. 获取数据库的连接
                conn = java.sql.DriverManager.getConnection("jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=GBK","root", null);// root是用户名,密码为空
                // 3. 获取表达式
                stmt = conn.createStatement();
                // 执行插入数据的 SQL
                int row = stmt.executeUpdate("insert into Student(username, password, age) values('张三', '1234', 20)");
                System.out.println("插入了 " + row);
                // 4. 执行 SQL
                rs = stmt.executeQuery("select * from Student");
                // 5. 显示结果集里面的数据
                while (rs.next())
                {
                    System.out.println("编号=" + rs.getInt(1));
                    System.out.println("学生姓名=" + rs.getString("username"));
                    System.out.println("密码=" + rs.getString("password"));
                    System.out.println("年龄=" + rs.getString("age"));
                }
                // 执行删除数据的 SQL, 被删除的记录的ID为7
                row = stmt.executeUpdate("delete from student where id = 7");
                System.out.println("删除了 " + row);
                }
            catch (SQLException e)
            {
                e.printStackTrace();
            } finally
                {
                    // 6. 释放资源,建议放在finally语句中确保都被关闭掉了
                    try
                    {
                        rs.close();
                    } catch (SQLException e)
                        {
                        }
                        try
                        {
                            stmt.close();
                        } catch (SQLException e)
                            {
                            }
                            try {
                                conn.close();
                                } catch (SQLException e)
                                    {
                                    }
                }
    }
}
    


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值