ERROR 1062 import sql file with primary and auto increment - mysql

I have a problem, I nedd to restore a sql file, but when I try to do this with mysql -u user -p --database test < file.sql I get this error ERROR 1062 (23000) at line 50: Duplicate entry '0' for key 'PRIMARY'
My first attribut is AUTO_INCREMENT and NOT NULL and PRIMARY
I have searched and the probem is in my sql file for my primary key I don't have value I have just simple quote. For example INSERT INTO log VALUES ('','app1','name','hello') as you can see my first value is only simple quote, how can I import this sql file without value beacause I have lot of lines in my file...
Definition of the table
CREATE TABLE `log` (
`id_log` int(11) NOT NULL AUTO_INCREMENT,
`application` varchar(20) NOT NULL,
`module` text NOT NULL,
`action` text NOT NULL,
PRIMARY KEY (`id_log`),
) ENGINE=InnoDB AUTO_INCREMENT=646 DEFAULT CHARSET=latin1;

You just need to rewrite your queries.
The query should look like this:
INSERT INTO log(application, module, action) VALUES ('app1','name','hello');
This will enter the remaining row in the table and consider the column id_log for auto-increment.

I would assume mysql is trying to cast '' to an int since it is an AUTO_INCREMENT field.
It casts it to 0 so for the first entry everything is fine, but on the second one, it already exists and you get the error.
You will have to replace the '' with actual, unique integer values or remove it altogether and add a columns list.

Related

getting error on insertion in mysql

i have created a table in mysql named as student with 2 columns named as "S-id int not null auto_increment 14012040" and "S-name varchar(45) not null unique" "primary key(S-id)"....
the table was successfully created..but after inserting one record into db ,on the next insertion it shows error like "dupliction of primary key is not allowed"...plz hlp me whta should i do..
in th below i am posting the screen shots....
creating table.
[1st insertion successfully addesd][2]
getting error
Your primary key S-id has a default value (14012040).
You only inserts values for S-name and studentcol columns therefore it will use the S-ids default value again and again.
When it runs first it can use the default value because it is not exists in the table. But second time it will throw an error.
You should use auto increment for S-id as Álvaro Touzón said.
UPDATE:
According to your comment, here is the working create script:
CREATE TABLE student (
S_id INT NOT NULL AUTO_INCREMENT
,S_name VARCHAR(45) NOT NULL
,PRIMARY KEY (S_id)
,UNIQUE INDEX S_name_UNIQUE(S_name ASC)
) AUTO_INCREMENT=14012040;
Working SQL fiddle here.

MySQL: Enforce an unique column without using an unique key

I have a column with data that exceeds MySQL's index length limit. Therefore, I can't use an unique key.
There's a solution here to the problem without using an unique key: MySQL: Insert record if not exists in table
However, in the comments, people are having issues with inserting the same value into multiple columns. In my case, a lot of my values are 0, so I'll get duplicate values very often.
I'm using Node and node-mysql to access the database. I'm thinking I can have a variable that keeps track of all values that are currently being inserted. Before inserting, I check if the value is currently being inserting. If so, I'll wait until it finishes inserting, then continue execution as if the value was originally inserted. However, I feel like this will be very error prone.
Here's part of my table schema:
CREATE TABLE `links` (
`id` int(10) UNSIGNED NOT NULL,
`url` varchar(2083) CHARACTER SET latin1 COLLATE latin1_general_cs NOT NULL,
`likes` int(10) UNSIGNED NOT NULL,
`tweets` int(10) UNSIGNED NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
ALTER TABLE `links`
ADD PRIMARY KEY (`id`),
ADD KEY `url` (`url`(50));
I cannot put an unique key on url because it can be 2083 bytes, which is over MySQL's key size limit. likes and tweets will often be 0, so the linked solution will not work.
Is there another possible solution?
If you phrase your INSERT in a certain way, you can make use of WHERE NOT EXISTS to check first if the URL does not exist before completing the insert:
INSERT INTO links (`url`, `likes`, `tweets`)
SELECT 'http://www.google.com', 10, 15 FROM DUAL
WHERE NOT EXISTS
(SELECT 1 FROM links WHERE url='http://www.google.com');
This assumes that the id column is a primary key/auto increment, and MySQL will automatically assign a value to it.

MySQL phpMyAdmin import from text without having the primary key?

How can I import data from a text file into a database without giving a primary key in the text file?
So I have a table where I have 3 columns: ID, firstName, lastName.
ID is auto incremented. I would like to read in the names from the text file like that:
John, Smith;
Michael, Jordan;
I don't want to use the primary key, as I don't know what will be the next primary key in the table, that should be done by auto increment.
If I use the text file like this, than I get the error message: Invalid column count...
The settings:
Columns separated with: ,
Columns enclosed with: "
Columns escaped with: \
Lines terminated with: ;
If I use the text file like this:
21, John, Smith; 22, Michael, Jordan;
The file can be imported (with the strange behavior that it tries to read the 3 empty line too, and sends an error, this one I don't understand either, but its a different topic)
This is the dump from the table:
CREATE TABLE IF NOT EXISTS `LoginData2` (
`FirstName` varchar(10) NOT NULL,
`LastName` varchar(10) NOT NULL,
`ID` int(4) NOT NULL AUTO_INCREMENT,
PRIMARY KEY (`ID`),
UNIQUE KEY `ID` (`ID`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;
Your spec says that Columns enclosed with: "
I added quotes around the columns (and took away the spaces):
"John","Smith";"Michael","Jordan";
AND put the auto increment ID column last. It imported fine with these settings.
This is a dump from my test table. Compare it with yours and see what is different. Also, try creating this table and import the data above to see how it works.
CREATE TABLE IF NOT EXISTS `users` (
`firstname` varchar(100) NOT NULL,
`lastname` varchar(100) NOT NULL,
`id` int(11) NOT NULL
) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8;
ALTER TABLE `users`
ADD PRIMARY KEY (`id`);
ALTER TABLE `users`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT,AUTO_INCREMENT=7;
UPDATE: When you import with phpMyAdmin, make sure the import setttings are correct. Your settings are not the default. I believe you need to choose csv using LOAD DATA and then fill in all the delimiters as you have stated.

MYSQL allowing me to insert nulls in PK and FK

I have been testing a database i am doing right now and i am noticing that it is letting me insert null values into fields that are part of a primary key, despite stating in the script that the value of the field should be NOT NULL. I am using MAC's MySQL Workbench, and I have been googling around and can't figure out why this is happening. (Maybe I am too brain-fried right now... I am even starting to doubt myself)
Part of the script of the database creation (these are the tables I have tested..):
DROP DATABASE IF EXISTS solytierra ;
CREATE DATABASE IF NOT EXISTS solytierra DEFAULT CHARACTER SET latin1 COLLATE latin1_swedish_ci ;
USE solytierra ;
DROP TABLE IF EXISTS solytierra.Cliente ;
CREATE TABLE IF NOT EXISTS solytierra.Cliente (
CIF VARCHAR(25) NOT NULL,
Nombre VARCHAR(100) NULL,
EmailGeneral VARCHAR(45) NULL,
Web VARCHAR(45) NULL,
Notas VARCHAR(150) NULL,
insertado Timestamp,
CONSTRAINT pk_Cliente PRIMARY KEY (CIF)
) ENGINE=InnoDB;
DROP TABLE IF EXISTS solytierra.PersonaContacto ;
CREATE TABLE IF NOT EXISTS solytierra.PersonaContacto (
Cliente_CIF VARCHAR(25) NOT NULL,
Nombre VARCHAR(50) NOT NULL,
Apellidos VARCHAR(100) NOT NULL,
Notas VARCHAR(150) NULL,
CONSTRAINT pk_PersonaContacto PRIMARY KEY (Cliente_CIF , Nombre , Apellidos),
CONSTRAINT fk_PersonaContacto_Cliente FOREIGN KEY (Cliente_CIF)
REFERENCES solytierra.Cliente (CIF)
ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB;
...
It will let me create Clients without CIF, "PersonaContacto" without Cliente_CIF or without "Nombre"....
I have also tested other databases that i already had that used to work and it is happening the same in an all them.
Got it!!
I don't know what sql mode i was running on by default, but with this:
SET sql_mode = TRADITIONAL;
It is now running perfectly! I didn't know that there were different sql modes! Thanks a lot to everyone for your time and efforts! It really helped me to see that the problem was in my workbench, not the code and look for the answer accordingly! I hope this thread will be useful for future beginners like me!
If the value being stored in the column CIF is actually a NULL, then the expression LENGTH(CIF) should also return NULL. (If it's a zero length string, then LENGTH(CIF) will return 0.
To verify:
SELECT c.CIF, LENGTH(c.CIF) FROM solytierra.Cliente c ;
SELECT c.CIF FROM solytierra.Cliente c WHERE c.CIF IS NULL;
If you are running an INSERT statement, I can't explain the behavior you are observing, either MySQL allowing a NULL value to be stored or MySQL providing an implicit default value.)
If it's a zero length string being stored, that's the behavior we would expect if the columns were not explicitly declared to be NOT NULL but were later declared to part of the primary key. It's also the behavior we'd expect if the column were defined NOT NULL DEFAULT ''.
When the NOT NULL is omitted from the column declaration and the column is later declared to be part of the PRIMARY KEY, MySQL will use an an implicit default value based on the datatype of the column (zero length string for VARCHAR, zero for an integer, etc.)
But I'm not able to reproduce the problem you report, with the table definitions you've posted.
I recommend you check the table definition by getting the output from:
SHOW CREATE TABLE solytierra.Cliente;

mySQL how to update and replace

I need to insert records, but if the records exist do a replace instead. Here is what I am currently using:
$sessionDate = date("Y-m-d H:i:s");
foreach($tmpVP as $sessionVP) {
$res = mysql_query("INSERT INTO sessions
(sessionID,sessionDate,sessionVS,sessionVP)
VALUES('$sessionID','$sessionDate','$sessionVS',
'$sessionVP')") ;
}
What I really need is to update any records matching sessionID, sessionVS, and sessionVP and insert new records that don't match.
EDIT:
Table definition
CREATE TABLE `sessions` (
`ID` bigint(20) NOT NULL auto_increment,
`sessionID` varchar(36) NOT NULL,
`sessionDate` datetime NOT NULL,
`sessionUser` bigint(20) NOT NULL,
`sessionVS` varchar(255) NOT NULL,
`sessionVP` bigint(20) NOT NULL,
`reserved` int(11) NOT NULL,
PRIMARY KEY (`ID`),
KEY `ID` (`ID`)
) ENGINE=MyISAM AUTO_INCREMENT=88 DEFAULT CHARSET=utf8
sessionID, sessionVP, and sessionVS are not unique. Sample:
sessionID sessionDate sessionUser sessionVS sessionVP
0t1m58q9ktejuhqlrjqglcoia0 2010-06-20 09:20:53 0 111111 144268736
0t1m58q9ktejuhqlrjqglcoia0 2010-06-20 09:20:53 0 111111 144268819
0t1m58q9ktejuhqlrjqglcoia0 2010-06-20 09:20:53 0 111111 144268880
So, if I have a new record with 0t1m58q9ktejuhqlrjqglcoia0, 111111, and `144268880' I need to update row #3 instead of adding row #4.
Firstly you should add a unique index on (sessionID, sessionVP, sessionVS). You can do this using the following command:
CREATE UNIQUE INDEX ux_sessions_sessionid_sessionvs_sessionvp
ON sessions (sessionID, sessionVS, sessionVP)
Then there are two relatively simple ways to insert or update in MySQL. The first is to use ON DUPLICATE UPDATE:
INSERT INTO sessions
(sessionID,sessionDate,sessionVS,sessionVP)
VALUES
('$sessionID', '$sessionDate', '$sessionVS', '$sessionVP')
ON DUPLICATE KEY UPDATE sessionDate = '$sessionDate'
There other is to use REPLACE:
REPLACE INTO sessions
(sessionID,sessionDate,sessionVS,sessionVP)
VALUES
('$sessionID', '$sessionDate', '$sessionVS', '$sessionVP')
The second is slightly more concise, but has the disadvantage that it internally causes a delete followed by an insert.
There are also a few other issues:
You don't need both a primary key index and an ordinary index on ID. Remove the ordinary index as it is redundant.
You may have an SQL vulnerability. If you have not already validated the input you might want to consider protecting yourself by using mysql_real_escape_string or intval as appropriate. Alternatively you could look at using query parameters.
You are not checking for error conditions. Consider using trigger_error so that if your query has an error you can see what the error is. Seeing the error message can save you a lot of time debugging.
mysql_query("...") or trigger_error(mysql_error());
You might take a look at INSERT ... ON DUPLICATE KEY UPDATE: http://dev.mysql.com/doc/refman/5.0/en/insert-on-duplicate.html
Add an unique key on (sessionID, sessionVS, sessionVP), then use REPLACE instead of INSERT (just substitute the word, syntax is the same).
Based on your table structure, I mean the primary keys you can use
$res = mysql_query("REPLACE INTO sessions
(sessionID,sessionDate,sessionVS,sessionVP)
VALUES('$sessionID','$sessionDate','$sessionVS',
'$sessionVP')") ;
Are the values part of the primary key? If yes, take a look at: http://dev.mysql.com/doc/refman/5.0/en/insert-on-duplicate.html