changed value on insert into table [closed] - c#

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
can someone tell me why when I insert into database this string 01-02-20070858430013, the result is -20070858430014
using (SqlConnection connection = new SqlConnection(con1))
{
connection.Open();
for (int i = 0; i <= lb_dadosbrutos.Items.Count; i++)
{
using (SqlCommand command = new SqlCommand("INSERT INTO dbo.dados(Dados) VALUES(" + lb_dadosbrutos.Items[i] + ")", connection))
{
//MessageBox.Show("INSERT INTO dbo.dados (Dados) VALUES (01-02-20070858430013)");// + range.Cells[i, 1].Value2.ToString() + ")");
command.ExecuteNonQuery();
}
}
}
sry first stack question
Edit:
Tnks all, yes i missing the ' ', omg

I think you are trying to store this value as a string but your code is storing as integer.
so your query is suppose to have this following query with this 01-02-20070858430013 quoted in a string before been placed in a values.
("INSERT INTO dbo.dados (Dados) VALUES ('01-02-20070858430013')")

Check you Table design.
You may set column type as Int.Change it to nvarchar

Related

I keep getting a syntax error when trying to insert a date into a comment string and updating the file [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 9 months ago.
Improve this question
var dat = DateTime.Now.ToString("MM/dd/yyyy");
comment = dat.ToString();
comment = comment += " ";
comment = comment += txtComment.Text + NewLine;
ssl = $"update dbo.steak set comment={comment} where fileid={r2}";
using (command = new SqlCommand(ssl, sqlConnection));
command.ExecuteNonQuery();
The text in txtComment.Text is "bad steak" and the error is incorrect syntax near 'bad'
The complete comment reads "06/03/2022 bad steak"
I have tried several different ways to write the comment but keep getting the error, always after the date in the string. Any ideas as to what I am doing wrong? Thanks for your help.
Parameterize the SQL
Fix the using (I use old style syntax for clarity
I used "fake" variables for clarity
This is not fully complete nor is this production ready but should demonstrate the basic principles and resolve your issue.
var dat = DateTime.Now.ToString("MM/dd/yyyy");
int r2 = 563; //fake an id
string sqlComnnection = "sometthing connection";
string txtComment = "Bad Steak'';drop table dbo.steak--";
var nowDate = DateTime.Now.ToString("MM/dd/yyyy");
string comment = $"{nowDate} {txtComment}{Environment.NewLine}";
var sqlText = #"
UPDATE dbo.steak
SET comment = #comment
WHERE fileid = #r2;
";
using (var connection = new SqlConnection(sqlComnnection))
{
using (var command = new SqlCommand())
{
connection.Open();
command.Parameters.Add(new SqlParameter("#comment", comment) {SqlDbType = SqlDbType.VarChar});
command.Parameters.Add(new SqlParameter("#r2", r2) {SqlDbType = SqlDbType.Int});
command.CommandText = sqlText;
command.CommandType = CommandType.Text;
command.ExecuteNonQuery();
}
}

How to get fields from database [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I want to get "Model" field and put on Textbox6. But how come it does not work.
The problem is that the Model field answer will not be shown in the textbox6
string Query = "Select * from S where Name = '" + TextBox1.Text + "' and Clientno = '" + TextBox2.Text + "';";
command.CommandText = Query;
OleDbDataReader reader = command.ExecuteReader();
while (reader.Read())
{
string Model = reader.GetString(reader.GetOrdinal("Model"));
TextBox6.Text = Model;
}
Couple of things:
Do not use select *, instead use select your columns names
Do not pass the .Text directly to your query, instead use parameterized sql expression
If Clientno is primary key column or , combination of Name and ClientNo gives unique result, use ExecuteScalar, you don't have to use ExecuteReader and loop through the datareader
Since you using only one field and want to fill in the textbox, modify your select statement to :
select top 1 Model from S where....
And if you are reading only one row you will not need a while loop. Further, you should always close the reader and put your SqlConnection inside using block. ( edited as suggested by the comments)
If (reader.Read())
{
TextBox6.Text = reader.GetString(reader.GetOrdinal("Model"));
reader.Close();
}

Trying to add a string value to a SQL database - help and advice [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I am trying to add a string value to a SQL database in SQL Server Managemnet Studio but this does not work.
What is the correct way to do this?
SqlCommand addProduct = new SqlCommand("INSERT INTO dbo.Test VALUES(" + txtProductName.Text + ");", sqlConnect);
try
{
addProduct.ExecuteNonQuery();
MessageBox.Show("This product has been succesfully added to the database!!");
}
catch (Exception error2)
{
MessageBox.Show(error2.ToString());
}
It seems that you forgot to include a quote for the added string. Something like this
SqlCommand addProduct = new SqlCommand("INSERT INTO dbo.Test VALUES('" + txtProductName.Text + "');", sqlConnect);
Let's consider what is being generated here:
addProduct = new SqlCommand("INSERT INTO dbo.Test VALUES(" + txtProductName.Text + ");", sqlConnect);
If the value of txtProductName.Text is "monkey nuts", then your SqlCommand will have a CommandText of:
INSERT INTO dbo.Test VALUES(monkey nuts);
This isn't valid SQL, as the string has not been quoted. Now, if the value of txtProductName.Text is "'foo');DROP TABLE Test; --", then your SqlCommand will have a CommandText of:
INSERT INTO dbo.Test VALUES('foo');DROP TABLE Test; --);
Which, whilst valid SQL (as I'd put the apostrophes in the text box to quote the string), isn't what you'd want to do either.
The safest approach is to use parametrisation, so something more like:
using (SqlCommand addProduct = new SqlCommand("INSERT INTO dbo.Test VALUES(#ProductName);", sqlConnect);
{
addProduct.Parameters.Add("#ProductName", SqlDbType.NVarChar, 50).Value = txtProductName.Text;
addProduct.ExecuteNonQuery();
MessageBox.Show("This product has been succesfully added to the database!!");
}

C# Run SQL Parameterized query - parameter not suplied [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 9 years ago.
Improve this question
I have a c# application. I am trying to run a parameterized query, please see below. However I keep getting the error message
"The parameterized query '(#dtStart date)SELECT * FROM
D_CORPACTIONS_MSCI WHERE [date_effe' expects the parameter '#dtStart',
which was not supplied."
I can't see why it is telling me this though?
DateTime dtStart = dtPrev;
using (_connection = new SqlConnection(_connectionString))
{
_connection.Open();
string cmdText = "SELECT * FROM D_CORPACTIONS_MSCI " +
"WHERE [date_effective] >= #dtStart " +
"AND [ca_status] ='" + caStatus + "'";
_command = new SqlCommand(cmdText, _connection);
_command.Parameters.Add("#dtStart", SqlDbType.Date);
Instead of Parameters.Add try Parameters.AddWithValue
_command.Parameters.AddWithValue("#dtStart", dtStart);
Or give a value to your parameter:
_command.Parameters.Add("#dtStart", SqlDbType.Date).Value = dtStart;

Select First table data and pass it to int value and print it in second table? ERRORS [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 8 years ago.
Improve this question
I want to select id from one table and insert that id to another table.
First I need to read my first table id and want to pass it to string.
Then I need to pass that string to second table.
String selQuery = "SELECT Id FROM MapDataImage WHERE Source='" + TextBox1.Text + "';";
{
int MId = int.TryParse(Id);
String QueryStr = "INSERT INTO User_Images VALUES (#Image)";
SqlCommand scmd = new SqlCommand(QueryStr, conn);
SqlDataReader sqldread = scmd.ExecuteReader();
//String QueryStr = "UPDATE MapDataImage SET Image = #Image WHERE Source='" + TextBox1.Text + "';";
//SqlCommand scmd = new SqlCommand(QueryStr, conn);
scmd.Parameters.Add("#Image", SqlDbType.VarBinary).Value = imgbytes;
scmd.ExecuteNonQuery();
}
so is this correct?
int MId = int.TryParse(Id); //the name id does not exist in current context?
but i want to retrieve particular id value from database
or
int MId = int.TryParse(#Id);
int MId = int.Parse("Id");
Will never work. "Id" is a string literal, it can never be an integer. I think you need to specify a variable
int mId = int.Parse(id);
Aside that, try using TryParse so it's safer.
Also use paramerterised queries on your SELECT statement to prevent SQL Injection.
Please post the rest of your code and I will adjust my answer to accomodate.
You don't create DataReaders objects by yourself. Instead you obtain a reference to DataReader object by invoking ExecuteReader method of Command class.
http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.executereader.aspx

Categories

Resources