`
473687880
  • 浏览: 485152 次
文章分类
社区版块
存档分类
最新评论

使用PreparedStatement的setString方法会自动在数据库相应表项后面补空格解决办法

 
阅读更多

数据库表的数据项如果设置为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) {
			// TODO 自动生成的 catch 块
			e.printStackTrace();
		}
		try {
			con = DriverManager.getConnection("jdbc:odbc:MySqlTable", "sa", "");
		} catch (SQLException e) {
			// TODO 自动生成的 catch 块
			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) {
			// TODO 自动生成的 catch 块
			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) {
			// TODO 自动生成的 catch 块
			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输出没有空格

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics