ASp.net - adding a new row to database - asp.net

I have written this code in visual basic. On executing no error is printed but the new row is not added to the database. I have tried using datasets also but that didnt work either. Any ideas?
Dim conSQL As SqlConnection = New SqlConnection
conSQL.ConnectionString = "Data Source=USER-PC\SQLEXPRESS;Initial Catalog=Phd;Integrated Security=True"
conSQL.Open()
Dim cmd As New SqlCommand("Insert into Phd_Student(student_id,student_name,student_email) values ('" + idnotextbox.Text + "','" + studnametextbox.Text + "','" + studemailtextbox.Text + "')" , conSQL)
cmd.ExecuteNonQuery()

There are only two possible outcomes of executing an insert; either it adds a record or you get an exception. So the alternatives in your case are:
The code that you showed is not executed at all.
You are catching the exception and ignoring it.
The actual code that you have is something different from what you posted.
You have created a trigger in the database that removes the record.
One of the values in the textboxes uses SQL injection to remove the added value*.
*) If you enter the value -1','','');delete Phd_Student where student_id='-1'-- in the id textbox, that would add a record and then remove it.

1- You should open the connection before executing the command.
try
conSQL.open()
Dim cmd As New SqlCommand("Insert into Phd_Student(student_id,student_name,student_email) values ('" + idnotextbox.Text + "','" + studnametextbox.Text + "','" + studemailtextbox.Text + "')" , conSQL)
cmd.ExecuteNonQuery()
Finally
conSQL.close()
end try
2- you should pass parameters to the query not like this way, to avoid SQL Injection.

first thing, make sure to call conSQL.Close() after cmd.ExecuteNonQuery() line.

Related

how to update entry in mysql table from asp.net?

In mysql workbench, I can type
UPDATE contact_log
SET note = 'test1'
WHERE customer = 'customer'
and it will update the customer's note.
WHen i try this in asp.net, it has no effect.
Try
conn.Open()
cmd.Connection = conn
Catch ex As Exception
End Try
cmd.CommandText = "UPDATE contact_log " +
"SET note = '" & TextBox2.Text & "'" +
"WHERE customer = '" & Request.QueryString("ID") & "'"
reader = cmd.ExecuteReader()
conn.Close()
conn.Dispose()
Some facts are that the connection string is correct, I can use select and bring back data with no problem, and the request.querystring("ID") brings back the customer name.
Is there a better way to update a mysql table from asp.net, or a way that actually works?
Many problems in your code.
Do not use string concatenation to build sql commands, but
parameterized query
Do not catch exceptions and swallow them
Use the appropriate using statement to close and dispose the
connection
Of course an INSERT/UPDATE/DELETE statement requires ExecuteNonQuery
To summarize I would change your code to this
Dim cmdText = "UPDATE contact_log SET note = #note WHERE customer = #cust"
Using conn = new MySqlConnection(connString)
Using cmd = new MySqlCommand(cmdText, conn)
conn.Open()
cmd.Parameters.AddWithValue("#note",TextBox2.Text)
cmd.Parameters.AddWithValue("#cust",Request.QueryString("ID"))
Dim rowsAffected = cmd.ExecuteNonQuery()
End Using
End Using
Parameterized query are very important because you avoid Sql Injections and parsing problems with string containing quotes (You will get a syntax error if the TextBox2 contains a text with a single quote)
The Using Statement will ensure that youR connection is properly closed and disposed also in case of exceptions and you avoid dangerous memory leaks and get lower usage of system resources
The exception is better handled on a upper level of your code where you could show a message to your user or write in an error log. Catching an exception and doing nothing is very bad because you will never learn what is the reason of failure in your code.
You're using the wrong command... You're WRITING to the database, not reading from it - You need to change from using a reader to an execution command....
Try this:
cmd.CommandText = "UPDATE contact_log " +
"SET note = '" & TextBox2.Text & "'" +
"WHERE customer = '" & Request.QueryString("ID") & "'"
cmd.ExecuteNonQuery()
conn.Close()
conn.Dispose()

second ExecuteReader() doesn't work

I have a code which checks the validity of user and then, if a user is valid it inserts certain values in the database.
My problem is when After I query my database to check if a user is valid and after that i try to pass the additional value to its account the flow stops when I invoke ExecuteReader() for the second time.
There is no error, or anything like that. I tried to substitute ExecuteReader() with ExecuteNoneQuery but still it's not working. I tried all the query in mysql command prompt they are working perfectly. I really can't understand what am I doing wrong there. Can anyone help me please?
Here is the code:
Try
myconn.Open()
Dim stquery As String = "SELECT * from accountstbl WHERE SE_ID = " & Id.Text
Dim smd = New MySqlCommand(stquery, myconn)
Dim myreader = smd.ExecuteReader()
If Not myreader.HasRows Then
errorUser.Visible = True
Else
myreader.Read()
Dim name As String = myreader.Item("user_name").ToString()
Dim stquery2 = "INSERT into backup VALUES (" & name & ", '" & Info & "')"
Dim smd2 = New MySqlCommand(stquery2, myconn)
Dim Myreader2 As MySqlDataReader
'smd.ExecuteNonQuery()'
'THE CODE STOPS HERE'
Myreader2 = smd2.ExecuteReader()
'Myreader2.Read()'
MsgBox("The BACKUP INFORMATION HAS BEEN SAVED")
End If
myconn.Close()
Catch ex As Exception
Dim ErrorMessage As String = "alert('" & ex.Message.ToString() & "');"
Page.ClientScript.RegisterStartupScript(Me.GetType(), "ErrorAlert", ErrorMessage, True)
myconn.Close()
End Try
Because your second query is an update, not a select, you need to execute it using the ExecuteNonQuery method. Your commented-out code shows an attempt to call ExecuteNonQuery but on the wrong command object (smd when it should be smd2). Try something like this instead:
myreader.Read()
Dim name As String = myreader.Item("user_name").ToString()
Dim stquery2 = "INSERT into backup VALUES (" & name & ", '" & Info & "')"
Dim smd2 = New MySqlCommand(stquery2, myconn)
smd2.ExecuteNonQuery()
The ExecuteNonQuery method returns the number of rows updated as an int value, so you can capture it if it's valuable to you. In your case it's probably not, but here's how you'd check anyway:
int rowsAdded = smd2.ExecuteNonQuery();
if (rowsAdded == 1) {
// expected this
} else {
// didn't expect this
}
Finally, concatenating strings to build SQL commands can leave you vulnerable to SQL Injection attacks. Please take a look at using parameterized queries. There's a decent example here.
If you want to execute nested Reader, you have to create another connection. You need somethig like
smd2 = New MySqlCommand(stquery2, myconn2)' myconn2 is another connection
OR
Set "MultipleActiveResultSets=True in your connection string.
Also, use ExecuteNonQuery() for Inserting
Dim name As String = myreader("user_name").ToString()
Dim stquery2 = "INSERT into backup VALUES ('" & name & "', '" & Info & "')"
Dim smd2 = New MySqlCommand(stquery2, myconn)
smd.ExecuteNonQuery()
Please use Parameterized query to avoid SQL Injection
The logic is that you need to close your first reader (myreader) before executing another reader (MyReader2) on the same connection.

Insert into SQL Server table gives me nothing

Very frustrating one... I have tried many combinations of ', " and so on but my insert command just refreshing the page.
What am I doing wrong?
Simple two text fields form with button. Under button I have this:
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["przychodniaConnectionString1"].ConnectionString);
con.Open();
string cmdStr = "INSERT INTO specyfik(speNazwa, speIlosc) values ('" + speNazwa.Text + "', '" + speIlosc.Text + "')";
SqlCommand insertCmd = new SqlCommand(cmdStr, con);
con.Close();
Zero errors while compiling and when testing, it seems like refreshed page. Nothing appears in db.
Don't you need to call insertCmd.ExecuteNonQuery() ?
...
SqlCommand insertCmd = new SqlCommand(cmdStr, con);
int row_affected = insertCmd.ExecuteNonQuery();
...
You need to execute your SqlCommand:
insertCmd.ExecuteNonQuery();
Also, you should look into parameterizing that query:
http://www.codinghorror.com/blog/2005/04/give-me-parameterized-sql-or-give-me-death.html
Will you like to make more improvements in your code using stored Proc and improvemnet in your code behind file ? Take a look at this answer...
https://stackoverflow.com/a/9595501/1209450

why this code enter two entries into the database

i have a code that retrieve some content and enter it the database :
MySqlConnection conn = new MySqlConnection(#"connection string");
MySqlCommand cmd = new MySqlCommand("INSERT INTO copy (id) VALUES ('" + Page.User.Identity.Name + "')", conn);
MySqlCommand cmd2 = new MySqlCommand("INSERT INTO copy (cv) VALUES ('" + mainEditor.Content.Replace("'", "''") + "')",conn);
conn.Open();
cmd.ExecuteNonQuery();
cmd2.ExecuteNonQuery();
conn.Close();
it connects and enters the data fine but it enters the data in two not one (it creates two rows instead of one)
i am using asp.net 3.5 and mysql 5.0
what am i doing wrong, thanks.
It's inserting two rows because you're executing two INSERT statements. Each time you run an INSERT it does just that: inserts a row.
I'm guessing you wanted to create a single row with both the id and cv fields populated. The SQL syntax for that is INSERT INTO copy (id, cv) VALUES ('x', 'y');
So:
MySqlCommand cmd = new MySqlCommand("INSERT INTO copy (id) VALUES ('" + Page.User.Identity.Name + "', '" + mainEditor.Content.Replace("'", "''") + "')",conn);
It's because two separate inserts are running. You can insert more than one value, try this:
MySqlCommand cmd = new MySqlCommand("INSERT INTO copy (id, cv) VALUES ('" + Page.User.Identity.Name + "', '" + mainEditor.Content.Replace("'", "''") + "')", conn);
You can comma separate the fields, and the values so it inserts into one record. Executing 2 insert commands will always create 2 records.
You didn't say which driver you're using so I'll use the documentation I found for dotConnect. I would try to use something along these lines (explanation of code below)
using( var conn = new MySqlConnection(#"connection string"))
using( cmd = new MySqlCommand("", conn) ){
cmd.CommandText = #"
INSERT INTO copy (id, cv)
VALUES (:name, :userContent)";
cmd.Parameters.Add("name", MySqlType.[correct type]]).Value = Page.User.Identity.Name;
cmd.Parameters.Add("userContent", MySqlType.[correct type], [column size]).Value = mainEditor.Content;
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
}
The use of the using construct is because MySqlConnection and MySqlCommand classes both implement the IDisposable interface so they need to be disposed of when you're done using them to avoid possible resource leaks.
The :name and :userContent is what I found in documentation for creating parametrized queries. This will allow the database driver to take care of escaping all of the special characters out of user input to avoid SQL injection attacks. This part is actually really important, there are some REALLY sophisticated SQL injection attacks out there, so there's a good chance simply escaping ' (as you were doing) isn't enough.

Web form is not updating tables, why?

I have a web application and on page is an update page to update some profile information. Below is the code I am using to update the table. But I think it is wrong. Does anything stick out? The connection string works cause it is used to read the database to get the profile information, I just removed it due to it containing password/login info for the db.
player is the class of properties that contains player information and ds is the dataset, but I would like to update the database itself online...
Dim connectionString As String = ""
Dim GigsterDBConnection As New System.Data.SqlClient.SqlConnection(connectionString)
GigsterDBConnection.Open()
Dim updatetoursql As String = "UPDATE PLAYERS SET FIRSTNAME = '" & player.FIRSTNAME & "', LASTNAME = '" & player.LASTNAME & "', ADDRESS = '" & player.ADDRESS & "', CITY = '" & player.CITY & "', ZIP = '" & player.ZIP & "', PHONE = '" & player.PHONE & "', EMAIL = '" & player.EMAIL & "', REFFEREDBY = '" & player.REFEREDBY & "' "
updatetoursql = updatetoursql & "PLAYERID = '" & player.PLAYERID & "';"
Dim cmd As New System.Data.SqlClient.SqlCommand(updatetoursql, GigsterDBConnection)
Dim sqlAdapter As New System.Data.SqlClient.SqlDataAdapter(cmd)
sqlAdapter.Update(ds, "PLAYERS")
I think the issue is something the 3 last lines of the code. am I doing it right or is their a better way?
Thanks
Well, apart from the glaring SQL injection issues waiting to bite you ..... (hint: use parametrized queries instead of concatenating together your SQL statement!!)
Dim cmd As New SqlCommand(updatetoursql, GigsterDBConnection)
Dim sqlAdapter As New SqlDataAdapter(cmd)
The problem here is: if you call the SqlDataAdapter constructor this way, what you're passing in is the select command (of the data adapter) - not the update command!
You need to do it this way:
Dim cmd As New SqlCommand(updatetoursql, GigsterDBConnection)
Dim sqlAdapter As New SqlDataAdapter()
sqlAdapter.UpdateCommand = cmd;
Now you've associated your UPDATE statement with the SqlDataAdapter.UpdateCommand and now it should work.
About the SQL injection: I'd strongly recommend using parametrized queries all the time - at least in production code. So instead of concatenating together your query, use this:
Dim updatetoursql As String =
"UPDATE PLAYERS SET FIRSTNAME = #FirstName, LASTNAME = #LastName, " &
"ADDRESS = #Address, CITY = #City, ZIP = #Zip, PHONE = #Phone " &
"EMAIL = #EMail, REFFEREDBY = #ReferredBy, PLAYERID = #PlayerID"
and then before you execute the command or the SqlDataAdapter.Update statement, set those parameters to the values you have. This is much safer and gives you less headaches and possibly even speed improvements (if that single Update query is only cached once in SQL Server memory).
Also, why go the long and complicated way of a SqlDataAdapter at all??
After you've created the SqlCommand and set all the parameters, just call cmd.ExecuteNonQuery(); and you're done!
Dim cmd As New SqlCommand(updatetoursql, GigsterDBConnection)
// set up the parameters here.....
cmd.Parameters.AddWithvalue("#FirstName", FirstName);
... etc.
// just call ExecuteNonQuery - and you're done!
cmd.ExecuteNonQuery();
The big thing that jumps up at me is how open to SQL Injection attacks this code is.
You should not build a SQL string in this manner, but use parameterized queries.
Other then that, you are constructing your adapter incorrectly, as the constructor will take the select command, not the update command. Create the command with the parameterless constructor then assign the command you have created to the UpdateCommand property.

Resources