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

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

6a1a3b92e6d4c5533ccfc0ba0fb9d816.png

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输出没有空格

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值