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.
Related
try
{
OleDbConnection myConnection = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\Users\\HP8200\\Desktop\\ELISA2014Data.mdb ;Persist Security Info=False;");
myConnection.Open();
// Create Oledb command to execute particular query
OleDbCommand myCommand = new OleDbCommand();
myCommand.Connection = myConnection;
// Query to create table with specified data columne
myCommand.CommandText = "CREATE TABLE UXZona([IDZona] int, [Morada] text)";
//myCommand.ExecuteNonQuery();
MessageBox.Show("Tabela criada");
}
catch
{
OleDbConnection myConnection = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\Users\\HP8200\\Desktop\\ELISA2014Data.mdb ;Persist Security Info=False;");
myConnection.Open();
OleDbCommand cmd = new OleDbCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "INSERT INTO UXZona (IDZona, Morada) VALUES ('" +
transaction.UnloadPlaceAddress.AddressID + "','" +
transaction.UnloadPlaceAddress.AddressLine2 + "')";
cmd.ExecuteNonQuery();
MessageBox.Show("Dados inseridos");
}
I need to insert data into the database but it isn't working. I launch the program and there are no errors, I do everything but when I check the database the table is empty.
UPDATE
Now when i launch the program I have this error:
"System.InvalidOperationException: 'ExecuteNonQuery: Connection property has not been initialized." on cmd.ExecuteNonQuery();
There are a number of things wrong! I give below corrected code:
try
{
bool success = false;
using (var myConnection = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\Users\\HP8200\\Desktop\\ELISA2014Data.mdb ;Persist Security Info=False;"))
{
// Create Oledb command to execute particular query
using (var myCommand = new OleDbCommand())
{
myCommand.Connection = myConnection;
// Query to create table with specified data columne
//myCommand.CommandText = "CREATE TABLE UXZona([IDZona] int, [Morada] text)";
//myCommand.ExecuteNonQuery();
//MessageBox.Show("Tabela criada");
cmd.CommandType = CommandType.Text;
cmd.CommandText = "INSERT INTO UXZona (IDZona, Morada) VALUES (#id, #morada)";
var param = cmd.CreateParameter();
param.ParameterName = "#id";
param.OleDbType = OleDbType.Integer;
param.Value = transaction.UnloadPlaceAddress.AddressID;
cmd.Parameters.Add(param);
param = cmd.CreateParameter();
param.ParameterName = "#morada";
param.OleDbType = OleDbType.VarChar;
param.Value = transaction.UnloadPlaceAddress.AddressLine2;
cmd.Parameters.Add(param);
myConnection.Open();
if (cmd.ExecuteNonQuery() == 1)
{
success = true;
}
}
}
if (success)
{
MessageBox.Show("Dados inseridos");
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
By way of explanation. I have commented out (but not deleted) all references to creating the table. Table creation and table insertion should be in two different routines. Normally you only create a table once, but insert is probably called many times.
I have placed the OleDbConnection and OleDbCommand within using loops. This is good practice, as they both implement IDisposable. Writing your code like this means that the Garbage Collector (GC) knows immediately that it can safely dispose of the objects after use.
I have changed the insert statement such that it takes parameters. This is highly recommended practice to safeguard against SQL Injection (if you do not know what this is please Google it). In fact Access is relatively immune from the worst forms of SQL Injection, because it rejects any command that contains multiple statements, but please get into good habits. With time you will progress to other databases which do not have this restriction.
I deliberately wait before opening the connection until just before it is needed. Connections consume resources, so it is good practice to use them as sparingly as possible. Also for this reason, I have moved your success message outside of the using loops. This means that the cleanup of resources is not waiting for the user to click OK in the message box.
Finally try catch is all well and good, but normally you want to know why the error occurred. Hence you add (Exception ex) to catch so that you can find the reason.
PS What I forgot to mention. In your original INSERT, you were surrounding both VALUES with single quotes. Only use single quotes for strings/text. Integers and other numbers require no quotes. If you quote them, the database will treat it as a string and you will get a data type error.
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).
How can I add a variable to my SQL string and run it against the server successfully? I want to run this statement through my C#
protected void RunSQLQuery(string salesman, string connectionString)
{
SqlConnection cnn;
SqlCommand cmd;
StringBuilder sql = new StringBuilder();
SqlDataReader reader;
cnn = new SqlConnection(connectionString);
sql = new StringBuilder();
sql.Append("update database ");
sql.Append("set shippdate = GetDate() ");
sql.Append("where salesman = "' + salesman + "'");
sql.Append("and managerapproval is not null ");
cnn.Open();
cmd = new SqlCommand(sql.ToString(), cnn);
reader = cmd.ExecuteReader();
reader.Close();
cmd.Dispose();
cnn.Close
}
This presents multiple compile errors underlining my +salesman+ code. The errors are:
Only assignment, call, increment, decrement, and new object
expressions can be used as a statement
; expected
) expected
Too many characters in character literal Newline in constant
You are not adding the string object that salesman refers, you are adding salesman as a string literal.
Just add it as a parameter like;
var cmd = new SqlCommand("update database set shippdate = GetDate() where salesman = #salesman");
cmd.Parameters.Add("#salesman", salesman);
...
And use ExecuteNonQuery to execute your command, not SqlDataReader. This SqlDataReader is for return some data.
But more important, you should always use parameterized queries. This kind of string concatenations are open for SQL Injection attacks.
Also use using statement to dispose your connection and command automatically instead of calling Close or Dispose methods manually.
As a full example;
protected void RunSQLQuery(string salesman, string connectionString)
{
using(var cnn = new SqlConnection(connectionString))
using(var cmd = cnn.CreateCommand())
{
cmd.CommandText = #"update database set shippdate = GetDate()
where salesman = #salesman";
// I assume your column is nvarchar
cmd.Parameters.Add("#salesman", SqlDbType.NVarChar).Value = salesman;
cnn.Open();
cmd.ExecuteNonQuery();
}
}
For myself, I always prefer to use SqlParameterCollection.Add(string, SqlDbType, Int32) overload to specify my parameter type and it's size but since you never mentioned your salesman column type, I couldn't post this in my example.
As you can also see from the syntax highlighting, the compile errors are caused because you did not escape the quotes properly in sql.Append("where salesman = "' + salesman + "'");.
As a side note, you should never insert strings into sql queries without first validating them, or you are open to sql injection, e.g. if i pass "''; drop table database;" as salesman parameter. It is better to use SqlParameter.
I would suggest using the AddWithValue method from your sql command combined with the UPPER function to make it case insensitive:
SqlCommand cmd = cnn.CreateCommand();
cmd.CommandText = "UPDATE database SET shippdate = GetDate() WHERE UPPER(salesman) = UPPER(#salesMan)";
cmd.Parameters.AddWithValue("#salesMan", salesman);
if (cnn.State.Equals(ConnectionState.Closed))
{
cnn.Open();
}
cmd.ExecuteNonQuery();
cnn.Close();
As mentioned in above answers, yes, writing queries in this way is not a good way to do it. But still if you want to do it that way only, you will have to change:
sql.Append("where salesman = "' + salesman + "'");
to
sql.Append("where salesman = '" + salesman + "'");
I was wondering if it is possible for the update button to save the changes made in the table. I wrote this code but I have no idea how it could possibly work
This is the code i wrote for the update button:
string conString = "Data Source=MIRANDA-PC;Initial Catalog=Futebol do Rosa;Integrated Security=True";
SqlConnection con = new SqlConnection(conString);
string selectSql = "Update Players$ set Player Name='" + dataGridView2.Text + "";
SqlCommand cmd = new SqlCommand(selectSql, con);
con.Open();
This is the table I want to update the values in:
Well, you just need to execute your query with ExecuteNonQuery.
But more important, you should always use parameterized queries. This kind of string concatenations are open for SQL Injection attacks.
Also use using statement to dispose your SqlConnection and SqlCommand.
And if your table or column names more than one word, you need to use them with [] as [Player Name]. And honestly, it is a little bit weird to use $ sign in a table name.
using(SqlConnection con = new SqlConnection(conString))
using(SqlCommand cmd = con.CreateCommand())
{
cmd.CommandText = "Update Players$ set [Player Name] = #name";
cmd.Parameters.Add("#name", SqlDbType.NVarChar, 16).Value = dataGridView2.Text;
con.Open();
cmd.ExecuteNonQuery();
}
You have to execute your SQL query with your db object.
dbinstance.ExecuteSqlCommand(string sqlcommand, object[] params);
This method is both for DDL and DML.
you can also use ExecuteNonQuery method.
cmd.CommandText = "Update Players$ set [Player Name] = #Playername";
cmd.Parameters.Add("#Playername", SqlDbType.NVarChar, 16).Value = dataGridView2.Text;
con.Open();
cmd.ExecuteNonQuery();
The best solution (if possible) to to convert your DAL (Data Access Layer) to Entity-framework based, instead of writing your own SQL queries. This is safe-by-design and never is vulnerable to SQL Injection of any kind.
Here is some mockup code:
using (AppEntities currDb = new AppEntities)
{
Players PlayerToEdit =
from player in currDb.Players
where player.PlayerID == lngPlayerID
select player.First();
PlayerToEdit.PlayerName = dataGridView2.Text;
currDb.SaveChanges();
}
You can read about it some more here:
https://msdn.microsoft.com/en-us/data/ef.aspx
I just learn how to connect C# and PostgresSQL.
I want to INSERT data from tb1(Textbox) and tb2 to database. But I don't know how to code
My previous code is SELECT from database.
this is my code
private void button1_Click(object sender, EventArgs e)
{
bool blnfound = false;
NpgsqlConnection conn = new NpgsqlConnection("Server=127.0.0.1;Port=5432;User Id=postgres;Password=admin123;Database=Login");
conn.Open();
NpgsqlCommand cmd = new NpgsqlCommand("SELECT * FROM login WHERE name='" + tb1.Text + "' and password = '" + tb2.Text + "'",conn);
NpgsqlDataReader dr = cmd.ExecuteReader();
if (dr.Read())
{
blnfound = true;
Form2 f5 = new Form2();
f5.Show();
this.Hide();
}
if (blnfound == false)
{
MessageBox.Show("Name or password is incorrect", "Message Box", MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1);
dr.Close();
conn.Close();
}
}
So please help me the code.
First off, you need to use the ExecuteNonQuery method rather than ExecuteReader since you're executing an INSERT rather than a SELECT statement. So, something like:
NpgsqlCommand cmd = new NpgsqlCommand("insert into table1 values(1, 1)", conn);
cmd.ExecuteNonQuery();
The ExecuteNonQuery method will also return the number of rows affected if that's important for you.
Second, you need to use SQL parameters rather than building an unsafe SQL string.
Use:
cmd.Parameters.Add(new NpgsqlParameter("name", tb1.Text));
cmd.Parameters.Add(new NpgsqlParameter("pw", tb2.Text));
To add a parameter to your query. You can now refer to it in your INSERT statement with :name or :pw, for example:
NpgsqlCommand cmd = new NpgsqlCommand("insert into login (Name, Password) values(:name, :pw)", conn);
cmd.ExecuteNonQuery();
Lastly, you might be interested in using an ORM rather than executing raw SQL statements. I'd check into the .NET Entity Framework or Castle Active Record, which is built on NHibernate. These libraries will allow you to query, update, create and delete data within your database without writing the actual SQL statements involved. It's a great way to get started, and will simply your code quite a bit!