数据库表的数据项如果设置为char、verchar类型,使用PreparedStatement向表中插入字符串数据时,数据会自动在后面添加空格,解决的办法是将数据项类型设置为nverchar。

- package Example;
-
- import java.sql.*;
-
- public class MyIcon
- {
- private Connection con;
- public void getConnection()
- {
- try {
- Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
- } catch (ClassNotFoundException e) {
-
- e.printStackTrace();
- }
- try {
- con = DriverManager.getConnection("jdbc:odbc:MySqlTable", "sa", "");
- } catch (SQLException e) {
-
- e.printStackTrace();
- }
- }
- public void showTable()
- {
- try {
- PreparedStatement sql = con.prepareStatement("select * from student");
- ResultSet result = sql.executeQuery();
- while(result.next())
- {
- System.out.print("id:" + result.getString(1));
- System.out.print(", name:" + result.getString(2));
- System.out.print(", sex:" + result.getString(3));
- System.out.println(", birthday:" + result.getString(4));
- }
- } catch (SQLException e) {
-
- e.printStackTrace();
- }
- }
- public void insertTable()
- {
- try {
- PreparedStatement sql = con.prepareStatement("insert into student values(?, ?, ?, ?)");
- sql.setInt(1, 25);
- sql.setString(2, "张一");
- sql.setString(3, "女");
- sql.setString(4, "2012-12-01");
- sql.executeUpdate();
- } catch (SQLException e) {
-
- e.printStackTrace();
- }
- }
- public static void main (String []args)
- {
- MyIcon icon = new MyIcon();
- icon.getConnection();
- System.out.println("修改前:");
- icon.showTable();
-
- icon.insertTable();
- System.out.println("插入后:");
- icon.showTable();
- }
- }
运行结果:
id:18, name:张三, sex:女, birthday:2012-12-02//表中已存在的数据
id:23, name:李某, sex:女, birthday:1999-10-20//表中已存在的数据
id:24, name:张一, sex:女, birthday:2002-12-01//表中已存在的数据
id:25, name:张一 , sex:女, birthday:2012-12-01 //插入的数据,其中name设置为verchar有空格,sex设置nverchar输出没有空格