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`)" +
")" ;
------解决方案--------------------
------解决方案--------------------
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);