最基本的JDBC模板及数据库乱码处理

初学JDBC

public class JDBCDemo1 {
    public static void main(String[] args) throws Exception {
        //1.加载驱动
        Class.forName("com.mysql.jdbc.Driver");
        //2、获取连接对象
        Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "123456");
        //3.获取执行SQL对象
        Statement statement = connection.createStatement();
        //4.执行SQL语句,并接收结果
        int result = statement.executeUpdate("insert into user(userid,username,sex)values(1,'张三','男');");
        /*//上述statement存在注入风险,执行效率也不是很高
          //以下方法有效避免SQL注入的风险,先编译,后运行
        String sql="insert  into user(userid,username,sex)values(5,'孙七','男')";
        PreparedStatement statement = connection.prepareStatement(sql);
        int result =statement.executeUpdate();*/
        //处理结果
        if(result == 1){
            System.out.println("注册成功!");
        }else {
            System.out.println("注册失败!");
        }
        //释放资源
        statement.close();
        connection.close();
    }
}

如若插入到数据库中的汉字出现乱码,可以将上面获取连接的代码改成:
Connection connection = DriverManager.getConnection(“jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF-8”, “root”, “123456”);
说明:出现乱码问题并非是这代码出现问题,而是你在安装数据库时选用的是mysql提供的默认字符latin1,使用改字符集的情况下,即使你创建数据库时选用的字符集是utf-8,使用JDBC插入有关中文的数据依旧会出现乱码,自己可以点开自己的mysql安装目录中去查看my.ini配置文件:盘符:\Program Files\MySQL\MySQL Server 5.1
在这里插入图片描述
在这里插入图片描述

提示

以上只是我自己的看法,如有雷同纯属意外。如有错误,也请谅解,勿喷!如有收获或疑问,欢迎点赞评论!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值