Connected database not updating - c#

I have connected my SQL database to my aspx.net form but when I entered the details in the form, it does not seem to update in my SQL Table. I've checked the codes and there doesn't seem to be any errors. Could anyone see what's wrong with my code?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data.Sql;
public partial class CustomerLogin : System.Web.UI.Page {
public string sqlTest = "Data Source=TEAFAMILY;Initial Catalog=Bolsen;Integrated Security=True";
protected void Page_Load(object sender, EventArgs e) {
}
static readonly string scriptSuccessNewAccount =
"<script language=\"javascript\">\n" +
"alert (\"Your account has been succesfully created - Thank You!\");\n" +
"</script>";
protected void Button1_Click1(object sender, EventArgs e) {
SqlConnection mDB = new SqlConnection(sqlTest);
mDB.Open();
Type csType = this.GetType();
SqlCommand cmd;
SqlDataReader rdr;
string strSQLSelect = "SELECT cEmail FROM Customers ORDER BY cEmail";
cmd = new SqlCommand(strSQLSelect, mDB);
Console.Write(cmd);
rdr = cmd.ExecuteReader();
//insert new record
string strSQLInsert = "INSERT INTO"
+ " Customers (cFirstname, cLastname, cNumber, cCompanyname, cAdd, cEmail, cPassword)"
+ " VALUES (#FN, #LN, #Num, #Cname, #Add, #Email, #Pw)";
cmd = new SqlCommand(strSQLInsert, mDB);
cmd.Parameters.AddWithValue("#FN", txtFN.Text);
cmd.Parameters.AddWithValue("#LN", txtLN.Text);
cmd.Parameters.AddWithValue("#Num", txtPN.Text);
cmd.Parameters.AddWithValue("#Cname", txtComp.Text);
cmd.Parameters.AddWithValue("#Add", txtCompAdd.Text);
cmd.Parameters.AddWithValue("#Email", txtEmail.Text);
cmd.Parameters.AddWithValue("#Pw", txtPW.Text);
cmd.ExecuteNonQuery();
mDB.Close();
ClientScript.RegisterStartupScript(csType, "Success", scriptSuccessNewAccount);
}
}

You are not closing your SqlDataReader. Asides from not calling rdr.Read() and getting any values, you need to call rdr.Close() before executing your second sql statement.
Per MSDN - While the SqlDataReader is being used, the associated SqlConnection is busy serving the SqlDataReader, and no other operations can be performed on the SqlConnection other than closing it. This is the case until the Close method of the SqlDataReader is called. For example, you cannot retrieve output parameters until after you call Close.

Related

Insert SQL data into table in ASP.Net Web Application via textbox

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.Sql;
using System.Data.SqlClient;
namespace todoassignment1
{
public partial class Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
Label1.Visible = false;
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
string valueUser = txtUsername.Text;
SqlConnection db = new SqlConnection(SqlDataSource1.ConnectionString);
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.Text;
//User is the name of the table, UserName is the column
cmd.CommandText = "INSERT User (UserName) VALUES ('" + valueUser + "')";
cmd.Connection = db;
db.Open();
try
{
cmd.Connection.Open();
cmd.ExecuteNonQuery();
Label1.Text = "Success writing into database!";
Label1.Visible = true;
}
catch (Exception ex)
{
Label1.Text = "Error writing into database.";
Console.WriteLine(ex.Message);
Label1.Visible = true;
}
finally
{
db.Close();
}
}
}
}
I added the SqlDataSource1 on the Default.aspx page, which seems to be done successfully as I can see the column names of the User table in the gridview. The table is empty, and all I'm trying to do is take input in a textbox and send it to the UserName column.
I'm not very good at debugging, but I have noticed a few errors which I have spent hours researching.
Things I've tried:
SQL SMS > tools > options > designers > CHECK prevent saving changes that require table re-creation
Added using System.Data;
Added cmd.Connection.Open();
Added an exception to be caught in the catch statement
Recreate entire database
Quadruple checked things like txtUsername being the correct textbox ID
Reconfigure SqlDataSource1 over and over, delete and recreate
Confirm that the connectionString in web.config is correct
Create the new SQLConnection with the exact string in web.config
SqlConnection db = new SqlConnection("Data Source=NAME-PC\\SQLEXPRESS;Initial Catalog=Assignment;Integrated Security=True");
Changed the insert line from concatenation to just "INSERT User (UserName) VALUES ('asdf')" to simplify code, still doesn't work.
Tried other syntax
cmd.CommandText = "INSERT INTO User (UserName) VALUES (#username)";
cmd.Parameters.Add("#username", SqlDbType.NVarChar, 50);
cmd.Parameters["#username"].Value = txtUsername.Text.ToString();
Clues from the debugger:
saw several "System.InvalidCastExceptions when digging through cmd in autos
errorCS0103: the name 'ExecuteNonQuery' does not exist in the current context
Always see System.InvalidOperationException after running
Please help.
static void BtnSubmit_Click(object sender, EventArgs e)
{
string valueUser = "test"; //txtUsername.Text;
using (SqlConnection db = new SqlConnection("Data Source=(localdb)\\MSSQLLocalDB;Initial Catalog=test;Integrated Security=True"))//SqlDataSource1.ConnectionString);
{
SqlCommand cmd = new SqlCommand("INSERT INTO dbo.[User] (UserName) VALUES (#valueUser)", db);
cmd.Parameters.Add("#valueUser", SqlDbType.VarChar, 50).Value = valueUser;
//cmd.CommandType = CommandType.Text;
//User is the name of the table, UserName is the column
//cmd.CommandText = "INSERT User (UserName) VALUES (#valueUser)";
//cmd.Connection = db;
db.Open();
try
{
//cmd.Connection.Open();
cmd.ExecuteNonQuery();
/*Label1.Text =*/
Console.WriteLine("Success writing into database!");
//Label1.Visible = true;
}
catch (Exception ex)
{
/*Label1.Text =*/
Console.WriteLine("Error writing into database.");
Console.WriteLine(ex.Message);
//Label1.Visible = true;
}
//finally
//{
//db.Close();
//}
}
}
A couple of issues.
The syntax for insert is INSERT INTO TABLE (COLUMNS) VALUES (VALUES) You had "INSERT User (UserName)"...
USER is a reserved word in SQL. If you insist upon using it as your table name it must be wrapped in square brackets.
You were opening the connection twice. Not really a problem per se, but unnecessary.
Always, always, always be using parameters.
I simplified things a little.
If you modify the method I've attached you should be able to copy paste it.

An exception of type 'System.Data.SqlClient.SqlException' occured in 'System.Data.dll but was not handled in user code

I have just started working on c#.net. below is my code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
public partial class Default2 : System.Web.UI.Page
{
//SqlConnection con = new SqlConnection("Data Source=ADMIN-PC\\SQLEXPRESS;Initial Catalog=register;Integrated Security=True");
protected void Page_Load(object sender, EventArgs e)
{
}
private const string strconneciton = "Data Source=ADMIN-PC\\SQLEXPRESS;Initial Catalog=register;Integrated Security=True";
SqlConnection con = new SqlConnection(strconneciton);
protected void Button1_Click(object sender, EventArgs e)
{
con.Open();
SqlCommand cmd = new SqlCommand("insert into user(uname, address,
email, number) values('" + TextBox1.Text + "', '" + TextBox2.Text + "', '" +
TextBox3.Text + "', '" +TextBox4.Text+ "')", con);
cmd.ExecuteNonQuery();
con.Close();
}
}
and I am getting this error
An exception of type 'System.Data.SqlClient.SqlException' occured in 'System.Data.dll but was not handled in user code
please help. I am using microsoft sql server management studio.
Do not hardcode sql queries:
They are difficult to read (so you can easily commit syntax error: in your case number is MS Sql's reserved word and should be put as [number])
They are prone to errors (e.g. what if TextBox2.Text contains an apostroph, ')
They are vulnerable to Sql Injection
I suggest extracting a method:
private void CoreInsert() {
//Done: wrap IDisposable into using, do not close explicitly
//TODO: do not hardcode strConnection, but read from settings
using (SqlConnection con = new SqlConnection(strConnection)) {
con.Open();
// Make sql
// 1. Readable: can you see a problem with "Number" now?
// 2. Parametrized
string sql =
#"insert into [user](
uname,
address,
email,
[number]) -- <- number is MS SQL's reserved word, put it as [number]
values(
#prm_uname,
#prm_address,
#prm_email,
#prm_number)";
//Done: wrap IDisposable into using
using (SqlCommand cmd = new SqlCommand(sql, con)) {
cmd.Parameters.AddWithValue("#prm_uname", TextBox1.Text);
cmd.Parameters.AddWithValue("#prm_address", TextBox2.Text);
cmd.Parameters.AddWithValue("#prm_email", TextBox3.Text);
//TODO: check actual field's type here
cmd.Parameters.AddWithValue("#prm_number", TextBox4.Text);
cmd.ExecuteNonQuery();
}
}
}
Then call the method
protected void Button1_Click(object sender, EventArgs e) {
CoreInsert();
}
Use Parameters function to add values to your command strings, always. I think it's problem about you are sending value "number" as char and you may define it as int at your database. So you can try to delete single qutoes from Textbox4.Text.
But if you want to make it better, use parameters. Like that.
SqlCommand cmd = new SqlCommand("insert into user(uname, address,
email, number) values(#uname,#address,#email,#number)", con);
cmd.Parameters.AddWithValue("#uname", TextBox1.Text);
cmd.Parameters.AddWithValue("#address", TextBox2.Text);
cmd.Parameters.AddWithValue("#email", TextBox3.Text);
cmd.Parameters.AddWithValue("#number", TextBox4.Text);
cmd.ExecuteNonQuery();
This will also prevent any SQL Injection problems.

asp.net registration page not working properly

I am creating a simple registration page and I get an error which I believe has to do with not being able to find the table I have created, yet I made it locally.
Here is the error I get:
An exception of type 'System.Data.SqlClient.SqlException' occurred in
System.Data.dll but was not handled in user code
Additional information: Incorrect syntax near the keyword 'Table'.
Any help would be fantastic.
Below I have posted the code that I have down so far:
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Configuration;
using System.Net.Mail;
public partial class Register : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
SqlConnection conn =
new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
conn.Open();
string checkuser = userchecker();
SqlCommand com = new SqlCommand(checkuser, conn);
int temp = changehere(com);
conn.Close();
if (temp == 1)
{
Response.Write("User Already Exists");
}
}
}
private string userchecker()
{
return "select count(*) from Table where UserName='" + TextBoxUN.Text + "'";
}
private static int changehere(SqlCommand com)
{
return Convert.ToInt32(com.ExecuteScalar().ToString());
}
protected void Button1_Click(object sender, EventArgs e)
{
try
{
Guid NEWguid = Guid.NewGuid();
SqlConnection conn =
new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
conn.Open();
string insertQuery = "insert into Table (ID, UserName, Email, Password) values (#ID, #Uname , #email, #password)";
SqlCommand com = new SqlCommand(insertQuery, conn);
com.Parameters.AddWithValue("#ID", NEWguid.ToString());
com.Parameters.AddWithValue("#Uname", TextBoxUN.Text);
com.Parameters.AddWithValue("#email", TextBoxEmail.Text);
com.Parameters.AddWithValue("#password", TextBoxPass.Text);
com.ExecuteNonQuery();
Response.Redirect("manager.aspx");
Response.Write("Registration successful");
conn.Close();
}
catch (Exception)
{
Response.Write("Error:");
}
}
protected void TextBoxEmail_TextChanged(object sender, EventArgs e)
{
}
}
Try this:
private string userchecker()
{
return "select count(*) from [Table] where UserName='" + TextBoxUN.Text + "'";
}
See the [] around Table, this is because Table is a reserved word in all SQL variants and you should escape it
Change the name of the table, table is a reserved word in SQL

SqlException was unhandled by user code error during execution

I am making page to display information from table (Like inbox page of any email website). But I am gettting the following error:
Incorrect syntax near the keyword 'to'.
Below is my C# code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
public partial class Inbox : System.Web.UI.Page
{
SqlConnection con = new SqlConnection();
SqlCommand cmmd = new SqlCommand();
protected void Page_Load(object sender, EventArgs e)
{
con.ConnectionString=#"Data Source=(LocalDB)\v11.0;AttachDbFilename=c:\Users\user\documents\visual studio 2012\WebSites\Email\App_Data\Database.mdf;Integrated Security=True";
con.Open();
label1.Text = Session["uid"].ToString();
cmmd.CommandText = "select frm from Inbox where to='" + Session["uid2"].ToString() + "'";
cmmd.Connection= con;
SqlDataAdapter daa = new SqlDataAdapter(cmmd);
DataTable dtt = new DataTable();
daa.Fill(dtt);
if(dtt.Rows.Count > 0)
{
label2.Text = dtt.Rows[0][3].ToString();
}
}
}
How to Solve this error?
Use "[to]" instead of just "to". It is problem when you use reserved term for field name.
It should be like this:
cmmd.CommandText = "select [frm] from [Inbox] where [to]='" + Session["uid2"].ToString() + "'";
EDIT:
And yes, for better security and less error-prone code you should use SqlParameter, something like that:
cmmd.CommandText = "select [frm] from [Inbox] where [to]=#SID"
cmmd.Parameters.Add("#SID", SqlDbType.Varchar);
cmmd.Parameters["#SID"].Value = Session["uid"].ToString();;

how to insert data into sql server in asp.net website?

I tried to insert data into sql server from my website build in vs 2008.For that I used button click event .I tried code shown in youtube but the code doesn't work .It shows error in my website.
The code in .aspx.cs file is
public partial class _Default : System.Web.UI.Page
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
protected void Page_Load(object sender, EventArgs e)
{
conn.Open();
}
protected void btnInsert_Click(object sender, EventArgs e)
{
SqlCommand cmd = new SqlCommand("insert into Insert values('"+txtCity.Text+"','"+txtFName.Text+"','"+txtLName.Text+"')",conn);
cmd.ExecuteNonQuery();
conn.Close();
Label1.Visible =true;
Label1.Text = "Your data inserted successfully";
txtCity.Text = "";
txtFName.Text = "";
txtLName.Text = "";
}
}
`
Okay, let's fix this code up just a little. You're getting there:
var cnnString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
var cmd = "insert into Insert values(#City,#FName,#LName)";
using (SqlConnection cnn = new SqlConnection(cnnString))
{
using (SqlCommand cmd = new SqlCommand(cmd, cnn))
{
cmd.Parameters.AddWithValue("#City",txtCity.Text);
cmd.Parameters.AddWithValue("#FName",txtFName.Text);
cmd.Parameters.AddWithValue("#LName",txtLName.Text);
cnn.Open();
cmd.ExecuteNonQuery();
}
}
A couple things to note about the modified code.
It's leveraging the using statement to ensure that resources are properly disposed.
It's parameterized to ensure that SQL Injection isn't a possibility.
It's not storing a connection object anywhere, get rid of that stored connection.
**
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
public partial class _Default : System.Web.UI.Page
{
SqlConnection con = new SqlConnection("Data Source=.\\SQLEXPRESS;Initial Catalog=mrinmoynandy;User ID=**;Password=****");
protected void Page_Load(object sender, EventArgs e)
{
}
protected void SumbitBtn_Click(object sender, EventArgs e)
{
SqlCommand cmd = new SqlCommand("insert into streg(Name,Father,Mother,Dob,Sex,Category,Maritial,Vill,Po,Ps,Dist,State,Pin,Country) values (#name,#father,#mother,#dob,#sex,#category,#maritial,#vill,#po,#ps,#dist,#state,#pin,#country)", con);
cmd.Parameters.AddWithValue(#"name", StNumTxt.Text);
cmd.Parameters.AddWithValue(#"father", FatNumTxt.Text);
cmd.Parameters.AddWithValue(#"mother", MotNumTxt.Text);
cmd.Parameters.AddWithValue(#"dob", DobRdp.SelectedDate);
cmd.Parameters.AddWithValue(#"sex", SexDdl.SelectedItem.Text);
cmd.Parameters.AddWithValue(#"category", CategoryDdl.SelectedItem.Text);
cmd.Parameters.AddWithValue(#"maritial", MaritialRbl.SelectedItem.Text);
cmd.Parameters.AddWithValue(#"vill", VillTxt.Text);
cmd.Parameters.AddWithValue(#"po", PoTxt.Text);
cmd.Parameters.AddWithValue(#"ps", PsTxt.Text);
cmd.Parameters.AddWithValue(#"dist", DistDdl.SelectedItem.Text);
cmd.Parameters.AddWithValue(#"state", StateTxt.Text);
cmd.Parameters.AddWithValue(#"pin", PinTxt.Text);
cmd.Parameters.AddWithValue(#"country", CountryTxt.Text);
con.Open();
con.Close();
}
}
Thanks
Mrinmoy Nandy
Phone No.: +91 9800451398
**
Creating procedure will avoid sql injection.
SQL
Create procedure insert
(#City,#FirstName,#LastName)
{
insert into tablename (City,FName,LName)
values(#City,#FirstName,#LastName)
}
C#
SqlConnection con=new sqlconnection("give ur connection string here");
sqlcommand cmd=new sqlcommand();
con.open();
cmd=new sqlcommand("insert",con);
cmd.commandtype=commandtype.storedprocedure;
cmd.parameters.addwithvalue("#City",txtCity.text);
cmd.parameters.addwithvalue("#FName",txtFName.text);
cmd.parameters.addwithvalue("#LNAme",txtLName.text);
cmd.ExecuteNonQuery();
con.close();

Categories

Resources