Incorrect decimal value: for column mysql - c#

Soo I have a application that can insert and update data into my MySQL database. Inserting the data works like a charm but when I try to update the data I receive the following exception:
Incorrect decimal value: '1,5' for column 'NumberOfHour' at row 1
This is the code im using for the update:
public void updateRecord(int activityID, string description, int projectID, int customerID, int hourID, int employeeID, int departmentID, int superviserID, string fixedFlex, string employeeType, decimal NumberOfHour, DateTime date, int CallID)
{
MySqlConnection conn = new MySqlConnection("database=hourregistration;server=193.78.140.90;username=Hour");
conn.Open();
using (MySqlCommand cmd = new MySqlCommand(string.Format("UPDATE activity SET Description='{0}',ProjectID='{1}',CustomerID='{2}',HourID='{3}',EmployeeID='{4}',DepartmentID='{5}',SuperviserID='{6}',FixedFlex='{7}',EmployeeType='{8}',NumberOfHour='{9}',Date='{10}',CallID='{11}' WHERE ActivityID='{12}';", description, projectID, customerID, hourID, employeeID, departmentID, superviserID, fixedFlex, employeeType, NumberOfHour, date.ToString("yyyy-MM-dd"), CallID, activityID),conn))
{
cmd.ExecuteNonQuery();
}
}
When I update the data without a decimal value (example: 5) its fine but when I try to user a comma (example: 5,1) I receive the exception..
Here is the Create table statement:
CREATE TABLE `activity` (
`ActivityID` int(10) unsigned NOT NULL AUTO_INCREMENT,
`Description` varchar(100) DEFAULT NULL,
`ProjectID` int(10) unsigned NOT NULL,
`CustomerID` int(10) unsigned DEFAULT NULL,
`HourID` varchar(1) NOT NULL DEFAULT '4',
`EmployeeID` int(10) unsigned NOT NULL,
`DepartmentID` int(10) unsigned DEFAULT NULL,
`SuperviserID` int(10) unsigned DEFAULT NULL,
`FixedFlex` varchar(10) DEFAULT NULL,
`EmployeeType` varchar(45) DEFAULT NULL,
`NumberOfHour` decimal(10,2) DEFAULT '0.00',
`Date` date DEFAULT NULL,
`External` tinyint(1) DEFAULT '0',
`CallID` int(10) DEFAULT '0',
PRIMARY KEY (`ActivityID`) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=54325 DEFAULT CHARSET=latin1 AVG_ROW_LENGTH=20 ROW_FORMAT=FIXED;

I think the problem is in the format. You are trying to add "1,5" - try with "1.5". Can you try with point instead of a comma.

You can replace comma to dot. (I think problem is in the format either)
string a = sum.Text;
a = a.Replace(",", ".");
sum.Text = a;

I solved it by my self. It happened when I changed the data type on MySQL and then changed it in DataSet. The solution that I found is deleting the column in the dataset, then adding the same column again, but by using the "configure" menu intem in the TableAdapter.
I hope this would be useful for you

I used this FILTER_FLAG_ALLOW_FRACTION
$value_in_usd=filter_input(INPUT_POST,'value_in_usd',FILTER_SANITIZE_NUMBER_FLOAT,FILTER_FLAG_ALLOW_FRACTION);
this $value_in_usd variable used in INSERT

Related

Create MySql database with TEXT column

I'm creating MySql database table from C# desktop application on remote server. I would like to make long records for columns content. I guess TEXT type must be suitable for this, but I'm not sure, how to set it from my createTableQuery string, instead varchar(120):
string createTableQuery = string.Format(#"CREATE TABLE `{0}` (
`id` smallint(5) unsigned NOT NULL AUTO_INCREMENT,
`slots` varchar(120) NOT NULL DEFAULT '',
`vectors` varchar(120) NOT NULL DEFAULT '',
PRIMARY KEY (`id`),
KEY `id` (`id`))
ENGINE = MyISAM AUTO_INCREMENT = 1 DEFAULT CHARSET = utf8;", "tab");
Or maybe I should use some different type...
Any advice and example would be useful
It would be:
string createTableQuery = string.Format(#"CREATE TABLE `{0}` (
`id` smallint(5) unsigned NOT NULL AUTO_INCREMENT,
`slots` TEXT NOT NULL DEFAULT '',
`vectors` TEXT NOT NULL DEFAULT '',
PRIMARY KEY (`id`),
KEY `id` (`id`))
ENGINE = MyISAM AUTO_INCREMENT = 1 DEFAULT CHARSET = utf8;", "tab");

Why returning column name or number of supplied values does not match table definition?

I am working with C# and I want to insert some values to my SQL Server database, here is my data base definition:
CREATE TABLE [dbo].[Users]
(
[Id] INT NOT NULL IDENTITY (1,1) PRIMARY KEY DEFAULT 1000,
[FullName] VARCHAR(50) NULL,
[Pseudo] VARCHAR(50) NULL,
[Mail] VARCHAR(50) NULL,
[Password] VARCHAR(50) NULL,
[Organism] VARCHAR(50) NULL,
[RegistredAt] DATETIME NULL,
[Confirmed] INT NULL
)
and this how I am trying to insert the values to the database using C#:
SqlCommand command = new SqlCommand("INSERT INTO Users VALUES(#FullName, #Pseudo, #Mail, #Password, #Organism, #RegistredAt, #Confirmed)", con);
command.Parameters.AddWithValue("#FullName", FullName);
command.Parameters.AddWithValue("#Pseudo", Pseudo);
command.Parameters.AddWithValue("#Mail", Mail);
command.Parameters.AddWithValue("#Password", Password);
command.Parameters.AddWithValue("#Organism", Organism);
command.Parameters.AddWithValue("#RegistredAt", DateTime.Now);
command.Parameters.AddWithValue("#Confirmed", Confirmed);
con.Open();
int i = command.ExecuteNonQuery();
con.Close();
When I execute the code, the instruction command.ExecuteNonQuery(); returns an exception:
Column name or number of supplied values does not match table definition
Where is the error?
You might need to supply the column names in your query:
INSERT INTO Users (FullName, Pseudo, Mail, Password, Organism, RegistredAt, Confirmed)
VALUES (#FullName, #Pseudo, #Mail, #Password, #Organism, #RegistredAt, #Confirmed)
If you don't supply the column names, it assumes you want to use all columns, including the ID field. That's the reason for the error -- you're supplying 7 values for a table with 8 columns. Since you are using a subset, you need to specify them.
Also, I'm not sure if you are at a stage where it can be fixed, but you have a typo in "RegistredAt" -- it should be "RegisteredAt".

How to insert multiple rows of one user with common ID (primary key) into SQL Server database?

I want to take educational qualification records in my Asp.net form. As I have to take the record of class 10th, 12th, graduation, master. So I have created four rows for this... and 5 columns (year of exam, board, percentage, total mark, division).
Now I want to insert all rows in database with one button click by maintaining the primary key common for one user in all four records.
Please help me with the code (C#)
You may want to look at using a Composite Primary Key. This is a Primary Key that uses multiple columns to compose a single key. There are arguments for and against this strategy. See: What are the pros and cons of using multi column primary keys?
As an example, if your table looks like this:
CREATE TABLE [dbo].[StudentExam]
(
[StudentId] INT NOT NULL PRIMARY KEY,
[Year] INT NOT NULL,
[Board] SOMEDATATYPE NOT NULL,
[Percentage] FLOAT NOT NULL,
[TotalMark] INT NOT NULL,
[Division] SOMEDATATYPE NOT NULL,
)
You can alter the schema to look like this instead:
CREATE TABLE [dbo].[StudentExam]
(
[StudentId] INT NOT NULL,
[Year] INT NOT NULL,
[Board] SOMEDATATYPE NOT NULL,
[Percentage] FLOAT NOT NULL,
[TotalMark] INT NOT NULL,
[Division] SOMEDATATYPE NOT NULL,
CONSTRAINT [PK_StudentExam] PRIMARY KEY ([StudentId], [Year])
)
By doing this, you are declaring that for any given row in this table, it is uniquely identified by the Student and Year together. You can still query on just the student, or just the year, but only together will they identify a row.
For more information on primary keys, see Create Primary Keys
Create Table Type in Sql
CREATE TYPE [dbo].[TypeName] AS TABLE(
[name1] [varchar](1000) NULL,
[name2] [varchar](1000) NULL,
[name3] [varchar](max) NULL
)
GO
Create Procedure in SQL :
ALTER PROCEDURE [dbo].[InsertData]
#TableType TypeName readonly
AS
INSERT INTO [dbo].[Table_Master]
(Tname1,Tname2,Tname3)
select name1,name2,name3 from #TableType
Then Go To Code Behind
OpenConnection();
sqlcmd.CommandType = CommandType.StoredProcedure;
sqlcmd.CommandText = spName;
sqlcmd.Connection = sqlconn;
SqlParameter tvpParam = sqlcmd.Parameters.AddWithValue("#Type", Your
Datatable);
tvpParam.SqlDbType = SqlDbType.Structured;
SqlParameter returnParameter = sqlcmd.Parameters.Add("RetVal",
SqlDbType.Int);
returnParameter.Direction = ParameterDirection.ReturnValue;
sqlcmd.ExecuteNonQuery();
int Result = (int)returnParameter.Value;
sqlcmd.Dispose();
return Result;
Pass your DT in Uper Code...It Will Work Completely

ASP.NET: Cannot add or update child row: a foreign key constraint fails

i have a strange issue in a asp.net application. I have two tables who save history of some variable changes, one with a foreign key to the other, but for some reason, mysql throws error while inserting to the second table
Cannot add or update a child row: a foreign key constraint fails (`FlowDB/tab_hist_vars_reas`, CONSTRAINT `tab_hist_vars_reas_ibfk_1` FOREIGN KEY (`HIST_REASIG_ID`) REFERENCES `tab_hist_reas` (`HIST_REASIG_ID`))
This is the code that makes the insert into the two tables (assume that local variables have values). I tested locally but when i install the site in the production environment it throws the above error.
string strcmd = "INSERT INTO tab_hist_reas (HIST_REASIG_INC,HIST_REASIG_FLOW,HIST_REASIG_STEP,HIST_REASIG_DATE,HIST_REASIG_USER)";
strcmd += string.Format("VALUES ({0}, '{1}', '{2}', NOW(), '{3}');", incident, flow, step, user);
db.executeNonQuery(strcmd);
strcmd = "SELECT last_insert_id() AS id";
int idHistory = (int)db.ExecuteScalar(strcmd);
foreach(var variable in lstVariables)
{
string strcmd = "INSERT INTO tab_hist_vars_reas (HIST_REASIG_ID,HIST_VAR_REASIG_VAR,HIST_VAR_REASIG_VALUE)";
strcmd += string.Format("VALUES ({0}, '{1}', '{2}');", idHistory, variable.Name, variable.Value);
db.executeNonQuery(strcmd);
}
Here are the table definitions.
CREATE TABLE `tab_hist_reas` (
`HIST_REASIG_ID` int(11) NOT NULL auto_increment,
`HIST_REASIG_INC` int(11) default NULL,
`HIST_REASIG_FLOW` varchar(150) default NULL,
`HIST_REASIG_STEP` varchar(150) default NULL,
`HIST_REASIG_DATE` datetime default NULL,
`HIST_REASIG_USER` varchar(150) default NULL,
PRIMARY KEY (`HIST_REASIG_ID`)
) ENGINE=InnoDB;
CREATE TABLE `tab_hist_vars_reas` (
`HIST_VAR_REASIG_ID` int(11) NOT NULL auto_increment,
`HIST_REASIG_ID` int(11) NOT NULL,
`HIST_VAR_REASIG_VAR` varchar(100) default NULL,
`HIST_VAR_REASIG_VALUE` varchar(100) default NULL,
PRIMARY KEY (`HIST_VAR_REASIG_ID`),
KEY `IND_HIST_VAR_REAS_ID_HIST` (`HIST_REASIG_ID`),
CONSTRAINT `tab_hist_vars_reas_ibfk_1` FOREIGN KEY (`HIST_REASIG_ID`) REFERENCES `tab_hist_reas` (`HIST_REASIG_ID`)
) ENGINE=InnoDB;
I tried replacing the last_insert_id() with ##identity but didn't work either. I tried executing the query directly into the database and it works fine.
A part from the Sql Injection problem that you have in your code, a probable reason for this behavior is the db variable. If this variable is some instance of a custom class that opens and closes the connection every time you call an ExecuteXXX method then you could face a problem with the SELECT LAST_INSERT_ID called in a different connection from the one that inserts the values in the first table.
You could try to merge the two initial commands to have them handled together by the same connection
string strcmd = #"INSERT INTO tab_hist_reas
(HIST_REASIG_INC,HIST_REASIG_FLOW,HIST_REASIG_STEP,
HIST_REASIG_DATE,HIST_REASIG_USER) ";
strcmd += string.Format("VALUES ({0}, '{1}', '{2}', NOW(), '{3}');", incident, flow, step, user);
strcmd += "SELECT last_insert_id() AS id";
int idHistory = (int)db.ExecuteScalar(strcmd);
In this way you exec just one command and you should be sure that the return from the SELECT last_insert_id() is effectively set to the current insert command.

Temporary table or Truncate fix table?

I have 5 fields obtained form two tables to insert into another table. Is it more efficient to do it with temporary table or with a fix table and truncate it each time I use it ?
If a temporary is more effective how to create within in c# a temporary table. Because this sql is not working ?
public static void CreateTempProd()
{
int result;
string sqlstr = "CREATE TEMPORARY TABLE ##tmptbl (id int NOT NULL AUTO_INCREMENT, dt DATETIME NOT NULL, qty int11 NOT NULL, rest int11 NOT NULL, nom VARCHAR(30) NOT NULL NOT NULL PRIMARY KEY id, ENGINE=MEMORY DEFAULT CHARSET=UTF8)";
MySqlConnection conn = new MySqlConnection(PublicVariables.cs);
MySqlCommand cmd = new MySqlCommand(sqlstr,conn);
MySqlTransaction trans;
conn.Open();
trans = conn.BeginTransaction();
try
{
result = cmd.ExecuteNonQuery();
}
catch (MySqlException e)
{
trans.Rollback();
MessageBox.Show(e.ToString());
return;
}
trans.Commit();
}
Your SQL syntax is a bit off;
CREATE TEMPORARY TABLE ##tmptbl ( -- ## needs quoting
id int NOT NULL AUTO_INCREMENT,
dt DATETIME NOT NULL,
qty int11 NOT NULL, -- int11 should be int(11)
rest int11 NOT NULL, -- int11 should be int(11)
nom VARCHAR(30) NOT NULL NOT NULL -- double NOT NULL
PRIMARY KEY id, -- id needs braces
ENGINE=MEMORY DEFAULT CHARSET=UTF8 -- should go outside the table braces
)
That is, it should be something like...
CREATE TEMPORARY TABLE `##tmptbl` (
id int NOT NULL AUTO_INCREMENT,
dt DATETIME NOT NULL,
qty int(11) NOT NULL,
rest int(11) NOT NULL,
nom VARCHAR(30) NOT NULL,
PRIMARY KEY (id)
)
ENGINE=MEMORY DEFAULT CHARSET=UTF8
A good idea is to just try running your exact query at the mysql command prompt, that would have caught this error and allowed you to fix it.

Categories

Resources