【环境见:在Eclipse中测试MySQL-JDBC(1)】
【声明:以后的文章中的mysql软件均是免安装版的,以后不做提示,除非特殊声明】
【默认情况下的jdbc-mysql驱动语句是:jdbc:mysql://localhost:3306/jdbcDemo】(mysql数据库jdbaDemo的字符集需要是utf8格式)
中文解决需要在上边的数据库名jdbcDemo的后面添加如下代码:
【
?characterEncoding=utf-8
或者
?characterEncoding=utf8
或者
?characterEncoding=UTF-8
或者
?characterEncoding=UTF8
】
【1 抛异常情况下的数据库插入数据】【执行下面的java文件的(run as)JUnit Test】后在数据库视图工具SQLyog中查看执行结果!
package com.flying.jdbc;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
import org.junit.Test;
public class Demo {
@Test
public void charu() throws Exception{
Class.forName("com.mysql.jdbc.Driver");
Connection ct = DriverManager.getConnection("jdbc:mysql://localhost:3306/jdbcDemo?characterEncoding=utf-8", "root", "root");
Statement st = ct.createStatement();
st.executeUpdate("insert into employee values(null,'等等',30)");
st.close();
ct.close();
}
}
【2 抓异常方式】
package com.flying.jdbc;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import org.junit.Test;
public class Demo {
@Test
public void charu() {
Connection ct =null;
Statement st =null;
try {
Class.forName("com.mysql.jdbc.Driver");
ct = DriverManager.getConnection("jdbc:mysql://localhost:3306/jdbcDemo?characterEncoding=utf8", "root", "root");
st = ct.createStatement();
st.executeUpdate("insert into employee values(null,'等等',30)");
} catch (Exception e) {
e.printStackTrace();
}finally{
try {
if (ct != null) {
ct.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
try {
if (st != null) {
st.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}