当前位置: 代码迷 >> J2EE >> java关于数据库操作疑点
  详细解决方案

java关于数据库操作疑点

热度:47   发布时间:2016-04-22 01:12:21.0
java关于数据库操作疑问
我在程序中创建了一个表:
String query = "create table student ( " + 
" snumber int ," +
" sname varchar(20) ," + 
" sgender varchar(4) ," +
" sage int ," + 
" smath double ," +
" senglish double ," + 
" schinese double ," + 
" sphysical double ," +
" schemistry double ," +
" spoint double , " +
" Primary key ( snumber )" +
")" ;

  表很简单,snumber 是主键。
但是在添加数据的时候,数据库没有控制重复的主键数据,仍然添加相同主键的数据,问问可能是什么问题。
添加数据命令:
String order = "insert into student (snumber,sname,sgender,sage,smath,senglish,schinese,sphysical,schemistry,spoint) values( " +
getstd.number + "," + 
"'" + getstd.name + "' , " + 
"'" + getstd.gender + "' , " + 
getstd.age + " , " + 
getstd.math + " , " + 
getstd.english + " , " + 
getstd.chinese + " , " + 
getstd.physical + " , " + 
getstd.chemistry + ", " + 
(double)((int)(getstd.mathPoint() * 1000))/1000 +
" )" ;

------解决方案--------------------
Java code
String query = "create table student ( " +  " snumber int primary key," +           //加上主键约束primary key" sname varchar(20) ," +  " sgender varchar(4) ," +" sage int ," +  " smath double ," +" senglish double ," +  " schinese double ," +  " sphysical double ," +" schemistry double ," +" spoint double , " +" Primary key ( snumber )" +")" ;
------解决方案--------------------
String query = "create table student ( " +
" snumber int ," +
" sname varchar(20) ," +
" sgender varchar(4) ," +
" sage int ," +
" smath double ," +
" senglish double ," +
" schinese double ," +
" sphysical double ," +
" schemistry double ," +
" spoint double , " +
" Primary key ( snumber ), UNIQUE KEY `idx_snumber` (`snumber`)" +
")" ;
------解决方案--------------------
探讨

引用:
应该是主键没添加成功。可能你的写法有误?如果主键添加成功 违反主键约束会提示报错的。
用这种试试 snumber int primary key,
把 Primary key (snumber) 这个删了。


JDriver = "sun.jdbc.odbc.JdbcOdbcDriver"
我的驱动, 添加 "snumber int primary ke……

------解决方案--------------------
LZ把建表和主键的语句分开试试。参照下面的

首先对 id 这个列,增加一个 NOT NULL 约束,然后再设置为主键。

1> ALTER TABLE test_tab
2> ALTER COLUMN id INT NOT NULL;

1> ALTER TABLE test_tab
2> ADD CONSTRAINT pk_test_tab PRIMARY KEY(id);
 
  相关解决方案