SQL Server query Insert into select and new data - c#

I need some correction with my query in C# & SQL Server.
I have a table called LoggedIn with name, password and clockin columns. I want it to insert into the table where name and password is from another table AND the clockin is the current time now.
string belepve = "INSERT INTO LoggedIn VALUES (SELECT name, password FROM Login WHERE password =" + Kod.login1 +" ,#MyDate";
SqlCommand command4 = new SqlCommand(belepve, con);
command4.Parameters.AddWithValue("#MyDate", DateTime.Now);
And then I just Execute the query.

There are multiple issues here.
First is the second parameter should also go as SqlParameter.
Second you have missing parenthesis at end.
Third you would need to specify the column names in which values should go in LoggedIn table.
Your working code would be something like:
string belepve = #"INSERT INTO LoggedIn (name,password,LoginDate)
VALUES (SELECT name,password,#MyDate
FROM Login
WHERE password =#Password
)";
SqlCommand command4 = new SqlCommand(belepve, con);
command4.Parameters.AddWithValue("#MyDate", DateTime.Now);
command4.Parameters.AddWithValue("#Password", Kod.login1);
Assuming that you have columns in LoggedIn table as named name,password and LoginDate, you might need to adjust the column names which you have actually in your table.
If you have same number of columns which you are already selecting then you can do it more simple like following:
SELECT name,password,#MyDate
INTO LoggedIn
FROM Login
WHERE password =#Password
But you need to be careful in the order of columns selecting otherwise value might go in different column than in what is expected.
Hope it helps.

Related

How Insert on table IF some value is in database

There is a syntax problem on Asp.Net when I try to run an insert on a table if I have a vlaue in another table that I look for.
I tried different queries and datareaders but that generates a problem, one of the 2 datareaders needs to be closed.
con.Open();
String insertRegInfo = "INSERT INTO Login (NumEmp,Nombre,Apellido,Codigo) values (#NumEmp, #Nombre,#Apellido,#Codigo) SELECT NumEmp from Empleados WHERE NumEmp = " + TxtNumEmp.Text +"" ;
MySqlCommand command = new MySqlCommand(insertRegInfo, con);
LblConfirm.Text = "Confirmado";
command.Parameters.AddWithValue("#NumEmp", TxtNumEmp.Text);
command.Parameters.AddWithValue("#Nombre", TxtNombre.Text);
command.Parameters.AddWithValue("#Apellido", TxtApellido.Text);
command.Parameters.AddWithValue("#Codigo", TxtCodigo.Text);
command.ExecuteNonQuery();
con.Close();
I expect to insert data into the table if any value is true.
Let me start saying that this is a terrible coding practice:
String insertRegInfo = "INSERT INTO Login (NumEmp,Nombre,Apellido,Codigo) values (#NumEmp, #Nombre,#Apellido,#Codigo) SELECT NumEmp from Empleados WHERE NumEmp = " + TxtNumEmp.Text +"" ;
Better is:
String insertRegInfo = "INSERT INTO Login (NumEmp,Nombre,Apellido,Codigo)
SELECT NumEmp,#Nombre,#Apellido,#Codigo from Empleados WHERE NumEmp = #NumEmp" ;
You should use parameters instead and better even Store Procedures.
However, to answer your question. All you need to do is match the number of columns of your SQL Command.
INSERT INTO Login (NumEmp,Nombre,Apellido,Codigo)
SELECT NumEmp, #Nombre,#Apellido,#Codigo from Empleados WHERE…
Note that I removed the values section from the insert. That is not required

SQLite table name from textbox value

I want to create a table name in SQLite based on the user inputted textbox value or a declared string value. For example:
cmd.CommandText = #"CREATE TABLE '"+Machine_Name.Text+"' AS (Date, Cal_Date) VALUES (#Date, #CalDate)";
I'm receiving a newline in constant error right before the AS. I know this may be bad database design but it would be helpful for me to do it this way.
Your query syntax seems to be mixed up.
If you want to create table, you have to provide the column spec (names and datatypes), or if you use create table as, a valid select query has to be used to define the column names/types.
The last part of your statement with the values clause is a valid form for an INSERT, but not for a create table.
See the Documentation here for details.
The syntax to create a table is the following
cmd.CommandText = #"CREATE TABLE '" + newTable + "'" +
"(DATE DATETIME, CAL_DATE VARCHAR(256))";
This of course assumes that your fields are a DateTime and a VarChar.
In other words, after the tablename you put, between parenthesys, the name of the columns and their datatype.
I suggest also to pay particular attention to the value your user types for the name of the new table. This liberty to type anything could be very dangerous and it is the basic building block when a malicious user tries to create an Sql Injection attack.
string ct = "Create table '" + Textbox1.Text +"'(Column1, Column2)";
SQLiteCommand createCommand1 = new SQLiteCommand(ct, sqliteCon);
createCommand1.ExecuteNonQuery();
sqliteCon.Close();
MessageBox.Show("Data Saved");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}

Insert query where table name is textbox text

I have a problem in button1 click event of inserting data into a table which table name be determined by whatever text is in textbox1
Should mean something like that:
tablename = textbox1.text;
sql = "INSERT INTO tablename ([itemserial], [itemname], [itemcount],[itemimage]) VALUES (#itemserial, #itemname, #itemcount, #itemimage)";
Having a textbox containing the name of your table is challenging because you should add extra care in handling this value. You should implement some kind of checking on this textbox value. A possible solution is to check against your database schema if the table typed by your user really exists.
You don't tell us which database system are you using so I will show an example using Sql Server
string tableName = textbox1.text;
using(SqlConnection cnn = new SqlConnection(... connectionstring...))
{
cnn.Open();
DataTable dt = cnn.GetSchema("TABLES");
DataRow[] rows = dt.Select("TABLE_NAME = '" + tableName + "'");
if(rows.Length > 0)
{
// Now you are sure to have a valid table in your textbox
// and could use the input value without risking an Sql Injection
string sql = "INSERT INTO [" + tableName + "] ([itemserial]," +
"[itemname],[itemcount],[itemimage]) " +
"VALUES(#itemserial,#itemname,#itemcount,#itemimage)";
.... the remainder of your code that use the query above....
}
else
MessageBox.Show("Please enter a valid name for your table");
Extending this approach you could change your TextBox to a ComboBox with ComboBoxStyle set to DropDownList (to block typing) and fill the ComboBox with the names returned by the GetSchema call above....
tablename = textbox1.text;
sql = string.Format("INSERT INTO {0} ([itemserial],[itemname],[itemcount],[itemimage])VALUES(#itemserial,#itemname,#itemcount,#itemimage)", tablename);
Although I would strongly recommend against this as it allows people to enter whatever they want into that textbox. Something like:
Robert; DROP TABLE Students;--
Which is discussed in more detail here:
How does the SQL injection from the "Bobby Tables" XKCD comic work?
Change your query like this
sql = "INSERT INTO "+tablename+" ([itemserial],[itemname],[itemcount],[itemimage]) VALUES (#itemserial,#itemname,#itemcount,#itemimage)";

how to write data to mysql database and ignore a column using c#

I have a C# program that connects to a remote mysql server and store date in a database on it.
In my db I have a column which I need it to have the CURRENT_TIMESTAMP of the server so I set the type of the column in my db to timestamp and the default value to CURRENT_TIMESTAMP the problem is when I ignore this column in my command I get this error "column count doesn't match value count at row 1" and if I send empty value, the value in the db becomes like this "0000-00-00 00:00:00".
here is my code
DBConnectMySQL.DBCommand.CommandText =
"INSERT INTO tbCard VALUES (#id,#Phone, #username, #CardDate)";
DBConnectMySQL.DBCommand.Parameters.AddWithValue("#id", "");
DBConnectMySQL.DBCommand.Parameters.AddWithValue("#Phone", number);
DBConnectMySQL.DBCommand.Parameters.AddWithValue("#username", UserName);
DBConnectMySQL.DBCommand.Parameters.AddWithValue("#CardDate", ""); // here is the problem
DBConnectMySQL.DBCommand();
DBConnectMySQL.DBCommand.Parameters.Clear();
I don't want to send the current time and date of the machine because I want to use the server time.
Specify which columns you want to insert and omit the column:
DBConnectMySQL.DBCommand.CommandText = "INSERT INTO tbCard(id, Phone, username) VALUES (#id,#Phone, #username)";
DBConnectMySQL.DBCommand.Parameters.AddWithValue("#id", "");
DBConnectMySQL.DBCommand.Parameters.AddWithValue("#Phone", number);
DBConnectMySQL.DBCommand.Parameters.AddWithValue("#username", UserName);
If you use an INSERT statement without saying which columns receives the values then you need to pass all the values for all the columns in the order in which the columns are defined in the table.
To avoid this problem just specify the column's names before the VALUES statement
string cmdText = #"INSERT INTO tbCard (col1, col2, col3)
VALUES (#id, #Phone, #username)";
DBConnectMySQL.DBCommand.CommandText = cmdText;
Also, if the ID column is an AUTO-INCREMENT column, then you shouldn't pass also this column and its value.

Move rows from table to table

I try to move rows that expired from one table to another with this:
MySqlConnection connect = new MySqlConnection(connectionStringMySql);
MySqlCommand cmd = new MySqlCommand();
cmd.Connection = connect;
cmd.Connection.Open();
string commandLine = #"INSERT INTO history SELECT clientid,userid,startdate,
enddate,first,city,imgurl,phone,type,seen
FROM events WHERE startdate<now();";
cmd.CommandText = commandLine;
cmd.ExecuteNonQuery();
cmd.Connection.Close();
The table are exactly the same (in each table I have id column with primary key, with auto increment) and when I run it i get this exception:
Column count doesn't match value count at row 1
Any idea why it crash?
The reason why you get the error is because the number of column on the table doesn't match on the number of values being inserted. This is usual when you have an auto-incrementing column on the table you are inserting.
In order to fix the problem, you need to specify the column name where the values will be inserted. Example,
INSERT INTO history (col1, col2,....) // << specify column names here
SELECT clientid, userid, startdate, enddate, first,
city, imgurl, phone, type, seen
FROM events
WHERE startdate < now()
I'm not pretty sure of the column names of table history that's why you need to change the column names to your valid names on your table.
For instance you have an auto-incrementing column on table history and you want to leave the query as is, you can pass NULL on the SELECT statement just to match the total number of columns to the total number of values. Example,
INSERT INTO history
SELECT NULL, clientid, userid, startdate, enddate, first,
city, imgurl, phone, type, seen
FROM events
WHERE startdate < now()
Keep in mind that in the case you won't specify the column names, the order of the values does matter.
Try :
string commandLine = #"INSERT INTO history (clientid,userid,startdate,enddate,first,city,imgurl,phone,type,seen) SELECT clientid,userid,startdate,enddate,first,city,imgurl,phone,type,seen FROM events WHERE startdate<now();";

Categories

Resources