Mysql DB Exception while saving data - mysql

I am using mysql query browser in that i set not null and default value for one column but while saving it is not considering default value it is showing error as column should not be null. how to solve this please help me

If you explicitly specify the column in an INSERT statement with a value of NULL, defaults are not considered.
For example, in the following query, even if there were a default for column foo, the engine will ignore it and try to insert a NULL:
INSERT INTO myTable(foo, bar) VALUES(NULL, 2);
Either omit the column from your INSERT statement entirely (recommended):
INSERT INTO myTable(bar) VALUES(2);
Or you can use a BEFORE INSERT trigger to catch the NULL value and replace it with what you want.

Related

MySql INSERT...ON DUPLICATE UPDATE with partial VALUES

I have a list of possibly-incomplete set of values that will be used to append to or update a MySql table using the INSERT...ON DUPLICATE KEY UPDATE construct. The requirements are as follows:
If an operation resolves to an INSERT and the field value IS supplied, use the value supplied;
If an operation resolves to an INSERT and the field value IS NOT supplied, use the field's table DEFAULT value;
If an operation resolves to an UPDATE and the field value IS supplied, use the value supplied;
If an operation resolves to an UPDATE and the field value IS NOT supplied, retain the current (table) field value.
I've come up with the following statement, but the clauses wrapped in ** are erroneous and I'm having difficulty expressing them:
INSERT INTO `test`
(`id`, `num`, `text`)
VALUES
('1', 100, 'aaa'),
('2', 200, DEFAULT),
('3', DEFAULT, 'ccc')
ON DUPLICATE KEY UPDATE
`num` = IF (**VALUES(`num`) = DEFAULT**, `num`, VALUES(`num`)),
`text` = IF (**VALUES(`text`) = DEFAULT**, `text`, VALUES(`text`));
Notes: id is the unique key. Both num and text have default (NOT NULL) values set.
Things I've tried, but aren't satisfactory:
Replacing DEFAULT in VALUES with NULL, and then test for, e.g., IF (VALUES (num) = NULL .... This works, but will insert NULL on INSERT (and generate a warning - e.g., "Column 'text' cannot be null"), which is not acceptable - I need to have the default value applied to the missing fields;
Using something like 'xxx' instead of DEFAULT for missing values, and testing for 'xxx' (STRCMP), but this will insert 'xxx' in case of INSERT;
I've not tried this as I can't find the command/proper syntax, but the idea is to test (in the IF clause) whether num and text in VALUES are literals (num or string) or a MySql keyword (i.e., DEFAULT) - possibly using regex? - and then act accordingly.
Of course, an alternative to the above might entail obtaining existing values from the database and/or hardcoding into the query the default values for the missing fields, but I trust the same result can be achieved more elegantly using a single MySql statement.
Thanks in advance for your feedback.

MySQL INSERT INTO results in Unknown Column in Field List

I am using the SQL feature phpMyAdmin to add 1 single record into my table. For simplicity, the record will be blank except for the 'symbol' field.
Table structure:
token_id = auto-increment, primary key
symbol = varchar(255)
every thing else is set to allow null entires, so should be irrelevant
I have tried the following queries, but all result in the same error:
unknown column 'symbol' in 'field list'
What I have tried:
INSERT INTO tokens (symbol) VALUES ('XYZ');
INSERT INTO tokens (symbol) VALUES ("XYZ");
INSERT INTO tokens (symbol) VALUES (XYZ);
INSERT INTO tokens.symbol VALUES ('XYZ');
INSERT INTO `tokens`.`symbol` VALUES ('XYZ');
Any suggestions?
Just for reference, trying the INSERT and using all columns and setting them to null results in the same exact error.
The correct format with backticks is
INSERT INTO tokens (symbol) VALUES ('XYZ');
FYI, I tried your first query on my server and worked fine so might be a problem with table structure.

Default values not working in phpmyadmin/mysql database

I can't get a table to accept "" or '' and use the default value. It is inserting NULL instead.
I am trying these commands in the direct input sql window.
INSERT INTO test01 VALUES ("", now(), "");
INSERT INTO test01 VALUES ('', now(), '');
But both just give NULL in the 3rd column. The structure is set to non-null with a default value of "yes". (Without quotation marks).
Here is a screenshot of the structure. You can see NULL is not checked.
http://garryjones.se/extras/so3.png
Default values only work if no value is inserted/updated. If you explicitly set it to an empty string (which is NOT the same as a NULL value) then it will end up with an empty string in the column. Instead of the code above you should eliminate the column from the INSERT statement at all:
INSERT INTO test01 (t1, t2) VALUES ('', now())
Other is already explain the reason here I am adding one more point you are also using current time stamp on update so do not need to use this column as well.
INSERT INTO test01 (t1) VALUES ('')
You could use the DEFAULT keyword: INSERT INTO test01 VALUES ("", now(), DEFAULT);

INSERT IGNORE - How can I tell if inserted?

I am going to need an SQL query that would INSERT .. ON DUPLICATE KEY UPDATE (or INSERT IGNORE INTO) my table.
I need to know if an update actually took place or rather a new row was inserted.
A good reference was this SO answer, unfortunately there's no answer to the action taken.
As for now I am using INSERT .. ON DUPLICATE KEY UPDATE:
INSERT INTO `tbl` (`CLIENT_ID`, `COMP_ID`, `DATETIME`) VALUES (12334,32,NOW())
ON DUPLICATE KEY UPDATE
`COMP_ID`=VALUES(`COMP_ID`), `DATETIME`=VALUES(`DATETIME`);";
and check the affected_rows value.
If affected_rows equals 1, means -> new row inserted
If affected_rows equals 2, means -> row updated
I'd like no change to happen in case of a duplicate, but I would like to know a duplicate exists.
Using MYSQL
Inspect the number of rows affected:
A return value of 1 means an INSERT occurred
A return value of 2 means an UPDATE occurred
If you're using JDBC, this is the int return value of the update() or execute() call.
All frameworks have a way of passing this value back to you, for example Hibernate's Query.executeUpdate() returns this int value.

SSIS Inserts not inserting the computed columns

I am using SSIS to insert a Excel file into a Sql Server Table. I believe it uses the Bulk insert, and as a result it doesn't insert into the 'CreationDate' and the 'ModificationDate' columns (both of which are computed columns with getdate() as the default).
Is there a way to get around this problem?
Also, just to be clear - both these date columns are not a part of excel. Here is the exact scenario:
My excel has two columns - code and description. My SQL Server table has 4 columns Code, Description, CreationDate, ModificationDate.
So, when the SSIS copies the data, it copies Code and Description, but the CreationDate and ModificationDate (which are SQL Server Computed Columns) are both empty.
You should use a normal column with a default constraint if you want to log creation
A computed column defined as GETDATE() will change every time you query it.
It is also impossible for a computed column to not be populated
So, assuming you mean "normal column with default", then you need stop sending NULL from SSIS which overrides the default
This is all demonstrated here:
CREATE TABLE #foo (
bar int NOT NULL,
testCol1Null datetime NULL DEFAULT GETDATE(),
testCol1NotNull datetime NOT NULL DEFAULT GETDATE(),
testCol2 AS GETDATE()
);
INSERT #foo (bar, testCol1Null) VALUES (1, NULL);
SELECT * FROM #foo;
WAITFOR DELAY '00:00:00.100';
SELECT * FROM #foo;
WAITFOR DELAY '00:00:00.100';
SELECT * FROM #foo;
DROP TABLE #foo;
Assuming you are using the Bulk Insert Task in SSIS, then you need to set "Keep nulls = off/unchecked" in the options page
You should have a default constraint on the column(s) that specifies get
col1 datetime default getdate()
There should also be an option for the bulk insert KEEPNULLS which should be turned off.
From Bulk Insert on MSDN:
Specifies that empty columns should retain a null value during the bulk-import operation, instead of having any default values for the
columns inserted. For more information, see Keeping Nulls or Using
Default Values During Bulk Import.
KEEPNULLS is also documented: http://msdn.microsoft.com/en-us/library/ms187887.aspx
Put in a Derived Column in your dataflow and populate the two missing columns with the values you want.
The value on a computed column doesn't physically exists on the database, it is calculated every time SQL Server needs to access it, that's why you can't inform a value to it on a insert.
What you need is a default column, which is a column that has a default value that's inserted if you don't inform any other value.
CreationDate datetime default getdate()
ModificationDate datetime default getdate()