Simple INSERT INTO a SQL Server using a C# application. Have debugged successfully down to the line
cmd.ExecuteNonQuery();
The program doesn't err or break, but nothing happens. I've explored the possibility of a dev/production database hiccup, but that does not seem to be it.
The code below is the Save button click. The names of database objects and connection parameters DataSource Table Catalog etc. are generalized, not verbatim.
string val1 = firstTextBox.Text;
string val2 = secondTextBox.Text;
string val3 = thirdTextBox.Text;
SqlConnection conn = new SqlConnection(#"Data Source=DataSource;Initial Catalog=Catalog;User ID=username;Password=password");
string sql = "INSERT INTO dbo.Table(col1, col2, col3) VALUES (" + val1 + "," + val2 + "," + val3 + "); ";
try
{
conn.Open();
SqlCommand cmd = new SqlCommand(sql, conn);
cmd.ExecuteNonQuery();
}
catch (System.Data.SqlClient.SqlException ex)
{
string msg = "Insert Error:";
msg += ex.Message;
}
finally
{
conn.Close();
}
Thanks for any help!
If your code was copied and pasted verbatim, your connection string is not valid.
Data Source=DataSource;Initial Catalog=Catalog;User ID=username;Password=password
You need to fill in the proper values for the DataSource, InitialCatalog, UserID, and Password values.
Also the query itself would be wrong unless you actually have a table named Table.
As an aside, you also should look into (Google search for) parameterized SQL queries, as well as using statements for proper disposal of resources (a.k.a. classes that implement IDisposable).
Related
So I tried making a code for adding 2 same data within 2 different tables which is
"studentinfo" and "logindb"
I tried doing this
enter code heprivate void buttonRegisterStudent_Click(object sender, EventArgs e)
{
String connection = "server=localhost;user id=root;password=root;persistsecurityinfo=True;database=votingdb";
//Inserting Data
String insertDataInfo = #"INSERT INTO studentinfo (firstname,lastname,username,password,email) values
('"+this.textBoxFirstName.Text+"','"+this.textBoxLastName.Text+"','"+this.textBoxUsername.Text+
"','"+ this.textBoxPassword.Text + "','"+ this.textBoxEmail.Text + "')";
String insertDataLogin = #"INSERT INTO logindb (username,password) values ('"+this.textBoxUsername.Text+"','"
+this.textBoxPassword.Text+"')";
//Connection
MySqlConnection con = new MySqlConnection(connection);
MySqlCommand datainfo = new MySqlCommand(insertDataInfo,con);
MySqlCommand datalogin = new MySqlCommand(insertDataLogin, con);
MySqlDataReader datareaderinfo;
MySqlDataReader datareaderlogin;
try
{
con.Open();
datareaderinfo = datainfo.ExecuteReader();
datareaderlogin = datalogin.ExecuteReader();
MessageBox.Show("Student Register Successfully!");
}
catch (Exception ex)
{
MessageBox.Show("Failed to Register" + ex);
}
}
Resulting to Error which says there may only one mysqldatareader in the code. How can I add the same data to the different tables?
Don't use a datareader if you don't want to read data. Simple use the ExecuteNonQuery on your command:
datainfo.ExecuteNonQuery();
And don't forget to open en close your connection!
You don't need a data reader for insert statements, you should simply use ExecuteNonQuery.
Please note that your current queries are a security hazard as they are vulnerable to SQL Injection attacks.
Instead of concatenating user inputs as strings to create your SQL statements, use parameterized queries.
For more information, read How can prepared statements protect from SQL injection attacks?
An improved version of the main parts in your code is this:
var insertDataInfo = #"INSERT INTO studentinfo (firstname,lastname,username,password,email) values
(#firstName, #lastName, #userName, #passwordHash, #email)";
var insertDataLogin = #"INSERT INTO logindb (username,password) values (#userName, #passwordHash)";
var datainfo = new MySqlCommand(insertDataInfo,con);
datainfo.Parameters.Add("#firstName", DbType.VarChar).Value = this.textBoxFirstName.Text;
datainfo.Parameters.Add("#lastName", DbType.VarChar).Value = this.textBoxLastName.Text;
datainfo.Parameters.Add("#userName", DbType.VarChar).Value = this.textBoxUsername.Text;
datainfo.Parameters.Add("#passwordHash", DbType.VarChar).Value = this.textBoxPassword.Text;
datainfo.Parameters.Add("#email", DbType.VarChar).Value = this.textBoxEmail.Text;
var datalogin = new MySqlCommand(insertDataLogin, con);
datalogin.Parameters.Add("#userName", DbType.VarChar).Value = this.textBoxUsername.Text;
datalogin.Parameters.Add("#passwordHash", DbType.VarChar).Value = this.textBoxPassword.Text;
datainfo.ExecuteNonQuery();
datalogin.ExecuteNonQuery();
Also, you are storing passwords as plain text in your database.
That's a really big security hole. You should be storing salted hash values of your passwords instead - but that's getting a little too broad for this answer so I'll leave that part up for you to read and apply.
I've been creating a class for buttons where you can add and delete rows from the table's database but it is my first time concatenate a string I have a suspicion that it is not working due to commandtext.
public static void deleteButton(string databaseName, string IDname, DataGridView dgv)
{
Helper.openConnection();
SqlCommand cmd = new SqlCommand();
cmd.Connection = Helper.cn;
string IDLocation = dgv.SelectedRows[0].Cells[0].Value.ToString();
cmd.CommandText = "delete from " + databaseName + " where " + IDname + " = " + IDLocation;
Helper.cn.Close();
MessageBox.Show("Successfully Deleted!");
}
public static void addButton(string databaseName, List<string> values, DataGridView dgv, bool isAdd)
{
Helper.openConnection();
SqlCommand cmd = new SqlCommand();
cmd.Connection = Helper.cn;
string message = isAdd == true? "Sucessfully Added" : "Sucessfully Edited";
string command = "insert into " + databaseName + " values(";
for (int i = 0; i < values.Count; i++)
{
command += values[i];
if(i != values.Count - 1) command += ", ";
}
command += ")";
cmd.CommandText = command;
MessageBox.Show(message);
Helper.cn.Close();
}
thank you for your time helping me.
Two problems:
You're using INSERT INTO [databaseName]. That should be INSERT INTO [tableName]. That's why it's not working.
Don't concatenate values into the SQL text. It opens the door for SQL injection, and it also makes it harder for the SQL server to reuse query plans. Instead, use query parameters. There is an example in the documentation.
I'll leave the design up to you and just attempt to answer the question. Have you actually looked at the command text? Have you tried to paste the command text into a query and run it manually? You need to quote string values. Also your functions and query use 'databaseName'. This should be a table name not a database name.
The commentary here is all on target, but that aside the key issue with your code is you are not doing anything. You have opened the connection, declared the SQL command, but then you don't execute it.
So yes, use parameters, but if you want your SQL to work you need to execute it:
string IDLocation = dgv.SelectedRows[0].Cells[0].Value.ToString();
cmd.CommandText = string.Format("delete from {0} where IDname = #ID", databaseName);
cmd.Parameters.AddWithValue("#ID", IDLocation);
Note you don't need quotes or anything when you use parameters, even on a non-numeric datatype.
And the feature of the evening, the missing link:
cmd.ExecuteNonQuery();
Same goes for your insert query -- be sure to run the execute method, and USE PARAMETERS!
I am trying to save a value from text box into sql database. I am having the error as shown on the picture. my code below:
public void datastore()
{
string Blerje, Shitje, Data;
Blerje = usdollar_buy.Text;
Shitje = usdollar_sell.Text;
Data = dateTimePicker.Text;
try
{
string constring = "Data Source=DELL;Initial Catalog=login_register;Integrated Security=True";
/* Declaring Connection Variable */
SqlConnection con = new SqlConnection(constring);
String sql = "INSERT into [login_register].[dbo].[BlerjeShitje] values ('" + Blerje + "','" + Shitje + "','" + Data + "')";
/* Checking Connection is Opend or not If its not open the Opens */
if (con.State != ConnectionState.Open)
con.Open();
SqlCommand cmd = new SqlCommand(sql, con);
/* Executing Stored Procedure */
cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show("Te dhenat u ruajten ne databaze");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
1. You might be having more columns in your table than mentioned values(3) in your query.
so it is always good to specify the column names in your query for which columns you are inserting the values.
Try This:
INSERT INTO [TableName](COL1,COl2,COL3)
Values(Value1,Value2,Value3);
2. As you mentioned your columsn are decimals, you are inserting them as as strings by enclosing the values within single quotes.
You should not enclose the decima values within single quotes.
Suggestion : Your query is open to SQL Injection Attacks.
I Would suggest you to use the Parameterised queries to avoid them.
You are missing the fields in your insert statement.
The database will try to determine the right columns and their order, but if you don't deliver all fields in the appropriate order, your query will fail.
So in short:
Deliver all fields in the correct order;
Or: add the fields you want to fill in the insert.
Sample:
String sql = "INSERT into [login_register].[dbo].[BlerjeShitje] (Blerje, Shitje, Data) values ('" + Blerje + "','" + Shitje + "','" + Data + "')";
change the datatype to (18,6) or so, whichever is suitable for you,
The second part of decimal data type shows how many digits do you require after the 'point'. In your case it's '0', so db is rounding it to nearest integer.
Source: http://msdn.microsoft.com/en-us/library/ms187746.aspx
I'm not sure why this is happening. I've seen the same issue online with little help out there to correct it.
When i run my query inside Access i get different values ranging from 0 - 10 but for some reason, it won't return that same value inside my code.
static int OrdersPerHour(string User)
{
int? OrdersPerHour = 0;
OleDbConnection conn = new OleDbConnection(strAccessConn);
DateTime curTime = DateTime.Now;
try
{
string query = "SELECT COUNT(ControlNumber) FROM Log WHERE DateChanged > #" + curTime.AddHours(-1) + "# AND User = '" + User + "' AND Log.EndStatus in ('Needs Review', 'Check Search', 'Vision Delivery', 'CA Review', '1TSI To Be Delivered');";
OleDbCommand dbcommand = new OleDbCommand(query, conn);
dbcommand.Connection.Open();
dbcommand.CommandType = CommandType.Text;
dbcommand.CommandText = query;
OrdersPerHour = (int?)dbcommand.ExecuteScalar();
}
catch (OleDbException ex)
{
}
finally
{
conn.Close();
}
return OrdersPerHour.Value;
}
Do not use string concatenation and the Access syntax to build your sql commands.
Use a simple parameterized query like this
string query = "SELECT COUNT(ControlNumber) FROM Log " +
"WHERE DateChanged > ? AND [User] = ? AND " +
"Log.EndStatus in ('Needs Review', 'Check Search', 'Vision Delivery'," +
"'CA Review', '1TSI To Be Delivered');";
OleDbCommand dbcommand = new OleDbCommand(query, conn);
dbcommand.Parameters.AddWithValue("#p1", curTime.AddHours(-1));
dbcommand.Parameters.AddWithValue("#p2", User);
dbcommand.Connection.Open();
dbcommand.CommandType = CommandType.Text;
OrdersPerHour = (int)dbcommand.ExecuteScalar();
In this way the burden to correctly interpret your value is passed to the Framework code that could format dates, decimals and strings according to your database requirements. By the way this will also prevent Sql Injection
Also, the word USER is a reserved keyword in Access SQL and thus you need to encapsulate it with square brackets
First and most important: Use Parametrized Queries!
Regarding your problem, I suggest you to debug the code:
Get the Commandtext of your "OleDbCommand dbcommand" and manually query to see if you get the same result.
Also, you should put your code within the try catch block, else it does not make sense at all.
HI i had manullay created textbox's and then used it for creating a new user. I am using SQL SERVER 2005 for backend and Visual Server 2008 for front..
I have this LoginAccount table which stores details of the new user created. When i Click the button(in which i have written code to create a new user through SQL insert),
string strConnection = ConfigurationManager.ConnectionStrings"FHDLConnectionString"].ToString();
SqlConnection sqlConnection = new SqlConnection(strConnection);
string username = TextBox1.Text;
string password = TextBox2.Text;
string confirmpass = TextBox3.Text;
string SQLQuery = "Select username From LoginAccount where '" + username + "'";
string SQLQuery1 = "Insert into LoginAccount values ('" + username + "','" + password + "')";
SqlCommand command = new SqlCommand(SQLQuery, sqlConnection);
SqlCommand command1 = new SqlCommand(SQLQuery1, sqlConnection);
sqlConnection.Open();
string CheckUsername = "";
if (password.ToString() != confirmpass.ToString())
{
Literal1.Text = " Password's does not match ";
}
else
{
try
{
CheckUsername = command.ExecuteScalar().ToString();
}
catch (Exception er)
{
Literal1.Text = " Username already exists ";
}
string insertQuery = "";
try
{
insertQuery = command1.ExecuteScalar().ToString();
Server.Transfer("Login_Created.aspx");
}
catch (Exception er)
{
Literal1.Text = " Could not create the user, Please retry with some other option ";
}
}
sqlConnection.Close();
I am getting these exception's
An expression of non-boolean type specified in a context where a condition is expected, near 'fhdl'
This error i got at the first catch
and
Object reference not set to an instance of an object.
This for at the last catch.
But the main thing is i am able to insert the username and password into the LoginAccount table!!!!!!! i.e. when i saw the table contents i could see the new user created in that table.
The other thing is This code executed perfectly once before but not now :(
Please could anyone tell me where am i going wrong?
I am new to C# with SQl ...
1 - ExecuteScalar() means that there's a return value. The insert doesn't have a return value. Use ExecuteNonQuery instead.
2 - Also, for the insert statement, specify the fields you're inserting into. Without specifying the fields, it's trying to insert into the first two columns of the table, which may not be username and password.
insert into LoginAccount(UserName, Password) values ....
3 - your select statement is incorrect.
select from LoginAccount where UserName='... You're missing the field name.
Three things:
Your first query doesn't do what you want it to. It resolves to:
Select username From LoginAccount where 'username'
You want to check the username against the database.
This code leaves you wide open to SQL Injection attacks. See this article for how to prevent them in C#.
On a similar note, you really don't want to store passwords in the clear in your database either.