Create MySql database with TEXT column - c#

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");

Related

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".

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.

Incorrect decimal value: for column mysql

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

Violation of PRIMARY KEY constraint 'PK_Calle'. Cannot insert duplicate key in object with autoincrement option activated

I'm migrating an old database which has no Identity constraints and I'm adding to the new one and everything worked fine, but when I checked the logs files I've created, I notice this error, the weird part of it is the table have Identity key with autoincrement of 1
The code I'm using is this:
var cmd1 = new SqlCommand();
cmd1.Parameters.Clear();
cmd1.Connection = mySqlConnection;
cmd1.CommandType = CommandType.Text;
cmd1.CommandText = #"INSERT INTO [Tomin].[TominPredial].[Calle]([Nombre],[Id_Colonia]"
+ ",[Id_User],[Id_Date])"
+ " VALUES(#Nombre,#Id_Colonia,#Id_User,#Id_Date)";
cmd1.Parameters.AddWithValue("#Nombre", nombreCalle);
cmd1.Parameters.AddWithValue("#Id_Colonia", id_col);
cmd1.Parameters.AddWithValue("#Id_User", "Admin");
cmd1.Parameters.AddWithValue("#Id_Date", DateTime.Now);
cmd1.ExecuteNonQuery();
I don't know what is this happening since I don't send the primary key because I suppose the autoincrement will set it for me, any idea what's going on?
The value that is the ID that throws the error begins in 1 and ends in 562, when I delete data, after doing it i use DBCC CHECKIDENT('Tomin.TominPredial.Calle', RESEED, 0)
CREATE TABLE TominPredial.Calle (
Id_Calle SMALLINT NOT NULL IDENTITY(1,1) CONSTRAINT PK_Calle PRIMARY KEY,
Nombre NVARCHAR(50) NOT NULL,
Id_Colonia SMALLINT NOT NULL CONSTRAINT FK_Calle_Colonia REFERENCES TominPredial.Colonia (Id_Colonia),
Id_User NVARCHAR(30) NOT NULL CONSTRAINT FK_Calle_User REFERENCES TominUsuario.Usuario (ID),
Id_Date DATETIME2 NOT NULL,
Id_Estatus TINYINT DEFAULT 1 NOT NULL CONSTRAINT FK_Calle_Estatus REFERENCES TominSistema.Estatus (Id_Estatus)
);
GO

AUTOINCREMENT does not work on OleDbCommand

I'm doing MS Access database file using OleDb. Here is the snippet:
OleDbCommand command = oleDbConnection.CreateCommand();
command.CommandText =
"CREATE TABLE MyTable (" +
"[Count] LONG NOT NULL PRIMARY KEY AUTOINCREMENT, " +
"[TimeAndDateTested] TIMESTAMP NOT NULL, " +
"[SerialNumber] VARCHAR(14) NOT NULL, " +
"[TestResult] BIT NOT NULL)";
command.ExecuteNonQuery();
Do you know what's wrong? Thanks.
In Access 2003, this statement will create the table structure I think you want. Notice I changed the name of the first field to Kount because Count is a reserved word in Access. You could enclose the name in square brackets to avoid ambiguity, but I prefer to just avoid using reserved words as object names. TIMESTAMP is recognized as a synonym for DATETIME. VARCHAR is recognized as a synonym for TEXT. BIT will get you a field type which Access calls Yes/No.
CREATE TABLE MyTable2 (
Kount COUNTER CONSTRAINT pkey PRIMARY KEY,
TimeAndDateTested TIMESTAMP NOT NULL,
SerialNumber VARCHAR(14) NOT NULL,
TestResult BIT NOT NULL);
I assigned a primary key constraint to Kount, and named the constraint as "pkey". Not Null and unique are implied by the primary key constraint, so you needn't specify them separately.
I change:
"[Count] LONG NOT NULL PRIMARY KEY AUTOINCREMENT, " +
with:
"[Count] IDENTITY NOT NULL PRIMARY KEY, " +
and it worked.
When using DDL against MS Access, you want to use COUNTER to specify an auto-incrementing integer Field.

Categories

Resources