when I developing just registration page this error occurred
error:An exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll but was not handled in user code
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.Configuration;
public partial class Registration : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["RegistrationConnectionString"].ConnectionString);
conn.Open();
String checkuser = "select count(*) from [UserData] where User Name='"+ TextBox1UN.Text +"'";
SqlCommand comm = new SqlCommand(checkuser,conn);
int temp = Convert.ToInt32(comm.ExecuteScalar().ToString());
if(temp==1)
{
Response.Write("user allready exists");
}
conn.Close();
}
}
protected void Button1_Click(object sender, EventArgs e)
{
try
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["RegistrationConnectionString"].ConnectionString);
conn.Open();
String InserQuery = "insert into [UserData](UserName,Email,Password,Country)values(#Uname,#email,#pass,#country)";
SqlCommand comm = new SqlCommand(InserQuery, conn);
comm.Parameters.AddWithValue("#Uname", TextBox1UN.Text);
comm.Parameters.AddWithValue("#email", TextBox2EI);
comm.Parameters.AddWithValue("#pass", TextBox3PW);
comm.Parameters.AddWithValue("#country", DropDownList1cont.SelectedItem.ToString());
comm.ExecuteNonQuery();
Response.Write("Registration is succesful");
Response.Write("Administrator.aspx");
conn.Close();
}
catch (SqlException ex)
{
Response.Write("Error:"+ex.ToString());
}
}
protected void TextBox1_TextChanged(object sender, EventArgs e)
{
}
}
aspx file:
<asp:SqlDataSource ID="SqlDataSourceRegistration"
runat="server"
ConnectionString="<%$ConnectionStrings:RegistrationConnectionString %>"
OnSelecting="SqlDataSourceRegistration_Selecting"
SelectCommand="SELECT * FROM [UserData]" >
</asp:SqlDataSource>
Your Query is not valid there is space between User Name and User is a keyword in sql. Your query should look like this
"select count(*) from [UserData] where UserName=#username";
Use Parameterized SQL
Add parameters to the command instead of concatenating values
comm.Parameters.AddWithValue("#username",TextBox1UN.Text);
A tip: Your code is very hackable / unsecure... because you put user input into the sql string you should use parameters instead.
You also have a space in your field name 'User Name' which I'm guessing is your issue so I put it as 'UserName'.
You should also put your code into a try catch statement so you can read the error.
try
{
SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["RegistrationConnectionString"].ConnectionString);
using (SqlCommand command = new SqlCommand(
"SELECT COUNT(*) from [UserData] where UserName= #Name", connection))
{
// Add new SqlParameter to the command.
command.Parameters.Add("#Name", SqlDbType.NVarChar).Value = TextBox1UN.Text;
int temp = Convert.ToInt32(command.ExecuteScalar().ToString());
if(temp==1)
{
Response.Write("user allready exists");
}
}
}
catch (Exception ex)
{
// Display the exception's data dictionary.
foreach (DictionaryEntry pair in ex.Data)
{
Console.WriteLine("{0} = {1}", pair.Key, pair.Value);
}
}
Related
I am creating a basic registration page using ASP.NET websites and C# and am trying to link the logins to a database I have created in Visual Studio 2017 and am constantly getting the error -
'System.NullReferenceException: 'Object reference not set to an instance of an object.'
System.Data.Common.DbCommand.ExecuteScalar(...) returned null.
and cannot understand why, code below any help appreciated.
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.Configuration;
public partial class Registration : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
ValidationSettings.UnobtrusiveValidationMode = UnobtrusiveValidationMode.None;
if (IsPostBack)
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["RegistrationConnectionString"].ConnectionString);
conn.Open();
string checkuser = "SELECT * FROM [Table] WHERE UserName='" + TextBoxUN.Text + "'";
SqlCommand com = new SqlCommand(checkuser, conn);
int temp = Convert.ToInt32(com.ExecuteScalar().ToString());
if (temp == 1)
{
Response.Write("User already exists, please enter a different username");
}
conn.Close();
}
}
protected void Button1_Click(object sender, EventArgs e)
{
try
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["RegistrationConnectionString"].ConnectionString);
conn.Open();
string insertQuery = "INSERT INTO Table (UserName,Email,Password,Country) values(#Uname ,#email , #password ,#country)";
SqlCommand com = new SqlCommand(insertQuery, conn);
com.Parameters.AddWithValue("#Uname" , TextBoxUN.Text);
com.Parameters.AddWithValue("#email" , TextBoxEmail.Text);
com.Parameters.AddWithValue("#password" , TextBoxPass.Text);
com.Parameters.AddWithValue("#country" , DropDownListCountry.SelectedItem.ToString());
com.ExecuteNonQuery();
Response.Redirect("Manager.aspx");
Response.Write("Registration Successful");
conn.Close();
}
catch (Exception ex)
{
Response.Write("Error:" + ex.ToString());
}
}
}```
If you want to check if user exists, there's no need in ExecuteScalar() with value:
int temp = Convert.ToInt32(com.ExecuteScalar().ToString());
when user doesn't exist, com.ExecuteScalar() returns null and you have a problem.
Code
private static bool UserExists(string userName) {
if (null == userName)
return false;
using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["RegistrationConnectionString"].ConnectionString)) {
conn.Open();
//DONE: parametrized query
//DONE: 1 instead of * - we don't want all columns to be returned
string sql =
#"select 1
from [Table]
where UserName = #userName";
using (SqlCommand com = new SqlCommand(sql, conn)) {
com.Parameters.Add("userName", SqlDbType.VarChar).Value = userName;
// user exists if cursor is not empty (we have at least one record)
return com.ExecuteScalar() != null;
}
}
}
protected void Page_Load(object sender, EventArgs e) {
ValidationSettings.UnobtrusiveValidationMode = UnobtrusiveValidationMode.None;
if (IsPostBack && UserExists(TextBoxUN.Text))
Response.Write("User already exists, please enter a different username");
}
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.
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
I'm trying to add values into database, but every time I try to add some thing i get an error in the ExecuteNonQuery() with the message "Connection must be valid and open."
And I don't know what to do!!!
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using MySql.Data.MySqlClient;
namespace ClientesClinica
{
public partial class frmCadastro : Form
{
MySqlConnection conect = new MySqlConnection("server = localhost; user id = root; database = clientes; password = '';");
public frmCadastro()
{
InitializeComponent();
}
private void frmCadastro_Load(object sender, EventArgs e)
{
}
private void btnCancela_Click(object sender, EventArgs e)
{
Close();
}
private void btnSalvar_Click(object sender, EventArgs e)
{
int cod;
string nome;
string end;
int tel;
cod = Convert.ToInt16(txtCodigo.Text);
nome = txtNome.Text;
end = txtEndereco.Text;
if (txtNome.Text == "")
{
MessageBox.Show("Favor digitar o nome");
}
if (txtCodigo.Text == "")
{
MessageBox.Show("Favor digitar o código");
}
conect.Close();
MySqlCommand insere = new MySqlCommand();
insere.CommandText = "INSERT INTO cliente(cod, nome, endereco) Values(#cod + ,'#nome', '#end');";
insere.Parameters.AddWithValue("#cod", cod);
insere.Parameters.AddWithValue("#nome", nome);
insere.Parameters.AddWithValue("#end", end);
conect.Open();
insere.ExecuteNonQuery();// THE ERROR IS HERE!!!!
conect.Close();
MessageBox.Show("Salvo");
}
You need to open your connection and supply it to the command as per MSDN: SQLCommand
string queryString = "SELECT OrderID, CustomerID FROM dbo.Orders;";
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlCommand command = new SqlCommand(queryString, connection); //<- See here the connection is passes to the command
connection.Open();
SqlDataReader reader = command.ExecuteReader();
try
{
while (reader.Read())
{
Console.WriteLine(String.Format("{0}, {1}",
reader[0], reader[1]));
}
}
finally
{
// Always call Close when done reading.
reader.Close();
}
}
Or for your usage:
conect.Open(); //<- Open Connection first
MySqlCommand insere = new MySqlCommand();
insere.Connection = conect; //<- Set the Commands connection
insere.CommandText = "INSERT INTO cliente(cod, nome, endereco) Values(#cod + ,'#nome', '#end');";
insere.Parameters.AddWithValue("#cod", cod);
insere.Parameters.AddWithValue("#nome", nome);
insere.Parameters.AddWithValue("#end", end);
insere.ExecuteNonQuery();
conect.Close();
this exception often raise cause of call the ExecuteNonQuery() method before connection opening
MySqlConnection con = new MySqlConnection(connection);
MySqlCommand command = con.CreateCommand();
command.CommandText="insert into stactoverflowtable (id,name) values('1','adil')";//suppose table name is stackoverflowtalbe
try
{
con.Open();
command.ExecuteNonQuery();
}
catch (Exception ex)
{
textBox1.Text = ex.Message;
}
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();