JDBC踩坑集合

JDBC向MySQL中添加字段时利用JUnit测试报错:java.lang.Exception: Method getConnection2() should be void,源码如下:

import org.junit.Test;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;

public class JDBCTest {

    @Test
    public Connection getConnection2() throws Exception {
        Properties properties = new Properties();

        InputStream in = this.getClass().getClassLoader().getResourceAsStream("JDBC.properties");
        properties.load(in);

        String driverClass = properties.getProperty("driver");
        String jdbcUrl = properties.getProperty("jdbcUrl");
        String user = properties.getProperty("user");
        String password = properties.getProperty("password");

        Class.forName(driverClass);

        return DriverManager.getConnection(jdbcUrl, user, password);
    }

    /**
     * 通过JDBC向指定的数据表中插入一条记录
     */
    @Test
    public void testStatement() throws Exception{
        //1.获取数据库链接
        Connection conn = getConnection2();

        //2.准备插入的SQL语句
        String sql = "INSERT INTO customers(`Name`,Email,Birth) VALUES('xiaoming','456@sina.com','2001-1-2');";

        //3.执行插入
        //(1)获取操作SQL语句的Statement对象:调用Connection的createStatement()方法来获取
        Statement statement = conn.createStatement();

        //(2)调用Statement对象的executeUpdate(sql)执行SQL语句进行插入
        statement.executeUpdate(sql);

        //(3)关闭Statement对象
        statement.close();

        //4.关闭连接
        conn.close();
    }
}

根据提示可以看到getConnection2()在测试单元里返回值必须是void,解决方法是注释掉getConnection2()方法上面的@Test语句

问题二:JDBC向表中添加字段时,使用中文出现乱码问题


在Navicat中右键表选择设计表,在选项中修改表的默认字符集



将默认的gb2321字符集改为utf8并保存

然后在添加代码url中加入?useUnicode=true&characterEncoding=utf8

重新添加数据,显示正常
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容