using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
public partial class _Default : System.Web.UI.Page
{
SqlConnection con = new SqlConnection(#"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\DELL\Documents\reg.mdf;Integra
ted Security=True;Connect Timeout=90");
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
con.Open();
SqlCommand cmd = new SqlCommand("insert into signup values" + "
(#id,#name)", con);
cmd.Parameters.AddWithValue("#id", TextBox1.Text);
cmd.Parameters.AddWithValue("#name", TextBox2.Text);
}
}
I used the above code. It has no errors but it doesn't save data in the table when I click on submit button. I'm using visual studio 2015 C# and storing data in localhost. Please help.
You need to call ExecuteNonQuery
con.Open();
SqlCommand cmd = new SqlCommand("insert into signup values" + "(#id,#name)", con);
cmd.Parameters.AddWithValue("#id", TextBox1.Text);
cmd.Parameters.AddWithValue("#name", TextBox2.Text);
cmd.ExecuteNonQuery();
Step-1
insert code in cs file
protected void Button1_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["conectionStr"].ConnectionString);
SqlCommand cmd = new SqlCommand("sp_insert_signup", conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new SqlParameter("#id", SqlDbType.Int)).Value = Convert.ToInt32(TextBox1.Text);
cmd.Parameters.Add(new SqlParameter("#name", SqlDbType.VarChar, 50)).Value = TextBox2.Text;
conn.Open();
try
{
int isSave = cmd.ExecuteNonQuery();
if (isSave > 0)
{
Response.Write("data save successfully");
}
else
{
Response.Write("data save operation failed");
}
}
catch (Exception ex)
{
Response.Write(ex.Message.ToString());
}
finally
{
conn.Close();
cmd.Dispose();
}
}
Related
I am developing windows application .Net in C#
DB stored inside the C# Application ".....\SQliteExample\SQliteExample\bin\Debug\MyDatabase.sqlite"
I can insert,update ,view and Delete to the table with the above code and view its contents in another activity with no troubles at all. However, when I restart the application I found that what I have inserted data before I restart the application has gone!
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 System.Data.SQLite;
namespace SQliteExample
{
public partial class Form1 : Form
{
SQLiteConnection connection = new SQLiteConnection("Data Source=MyDatabase.sqlite;Version=3;");
public Form1()
{
InitializeComponent();
SQLiteConnection.CreateFile("MyDatabase.sqlite");
connection.Open();
string sql = "create table Employee1 (EmpID int,EmpName varchar(20), age int,Salary int,Phone int , Address Varchar(20))";
SQLiteCommand command = new SQLiteCommand(sql, connection);
command.ExecuteNonQuery();
connection.Close();
}
private void btnSave_Click(object sender, EventArgs e)
{
if (connection.State != ConnectionState.Open)
connection.Open();
string sql1 = "insert into Employee1 (EmpID,EmpName,Age,Salary,Phone,Address) values (?,?,?,?,?,?)";
SQLiteCommand command = connection.CreateCommand();
command.CommandText = sql1;
command.Parameters.AddWithValue("EmpID", textBox1.Text);
command.Parameters.AddWithValue("EmpName", textBox2.Text);
command.Parameters.AddWithValue("Age", textBox3.Text);
command.Parameters.AddWithValue("Salary", textBox4.Text);
command.Parameters.AddWithValue("Phone", textBox5.Text);
command.Parameters.AddWithValue("Address", textBox6.Text);
command.ExecuteNonQuery();
connection.Close();
MessageBox.Show("Data Saved");
Clear();
View();
}
private void Clear()
{
textBox1.Text = string.Empty;
textBox2.Text = string.Empty;
textBox3.Text = string.Empty;
textBox4.Text = string.Empty;
textBox5.Text = string.Empty;
textBox6.Text = string.Empty;
}
private void View()
{
string sql3 = "select * from Employee1 order by EmpID asc";
SQLiteCommand command3 = new SQLiteCommand(sql3, connection);
DataTable dt = new DataTable();
SQLiteDataAdapter da = new SQLiteDataAdapter(command3);
da.Fill(dt);
dataGridView1.DataSource = dt;
connection.Close();
}
private void btnSelect_Click(object sender, EventArgs e)
{
View();
}
private void btnDelete_Click(object sender, EventArgs e)
{
if (!string.IsNullOrEmpty(textBox1.Text))
{
if (connection.State != ConnectionState.Open)
connection.Open();
string sql1 = "delete from Employee1 where EmpID = ?";
SQLiteCommand command = connection.CreateCommand();
command.CommandText = sql1;
command.Parameters.AddWithValue("EmpID", int.Parse(textBox1.Text));
command.ExecuteNonQuery();
connection.Close();
Clear();
View();
}
else
{
MessageBox.Show("Please Enter EmpID");
}
}
}
}
Thanks in Advance,
On recompilation you recreate the database file and recreate the table "employee". Therefore all your previous data is lost.
Registering page accepts usernames that are already included in database, even though I included code to prevent that:
string checkuser = "SELECT count(*) FROM Customers WHERE CustUserName='" + txtCustUserName.Text + "'";
SqlCommand com = new SqlCommand(checkuser, conn);
int temp = Convert.ToInt32(com.ExecuteScalar().ToString());
if (temp > 0)
{
Response.Write("User already exists");
}
This is the whole code for register page:
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;
using System.Configuration;
public partial class Registration : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
this.UnobtrusiveValidationMode = System.Web.UI.UnobtrusiveValidationMode.None;
if (IsPostBack)
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["RegistrationDatabaseConnectionString"].ConnectionString);
conn.Open();
string checkuser = "SELECT count(*) FROM Customers WHERE CustUserName='" + txtCustUserName.Text + "'";
SqlCommand com = new SqlCommand(checkuser, conn);
int temp = Convert.ToInt32(com.ExecuteScalar().ToString());
if (temp > 0)
{
Response.Write("User already exists");
}
conn.Close();
}
}
protected void Button1_Click(object sender, EventArgs e)
{
try
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["RegistrationDatabaseConnectionString"].ConnectionString);
conn.Open();
string insertQuery = "INSERT into Customers (CustFirstName, CustLastName, CustAddress, CustCity, CustProv, CustPostal, CustCountry, CustHomePhone, CustBusPhone, CustEmail, CustUserName, CustPassword) values (#custFirstName ,#custLastName ,#custAddress ,#custCity ,#custProv ,#custPostal, #custCountry ,#custHomePhone ,#custBusPhone ,#custEmail ,#custUserName ,#custPassword)";
SqlCommand com = new SqlCommand(insertQuery, conn);
com.Parameters.AddWithValue("#custFirstName", txtCustFirstName.Text);
com.Parameters.AddWithValue("#custLastName", txtCustLastName.Text);
com.Parameters.AddWithValue("#custAddress", txtCustAddress.Text);
com.Parameters.AddWithValue("#custCity", txtCustCity.Text);
com.Parameters.AddWithValue("#custProv", txtCustProv.Text);
com.Parameters.AddWithValue("#custPostal", txtCustPostal.Text);
com.Parameters.AddWithValue("#custCountry", txtCustCountry.Text);
com.Parameters.AddWithValue("#custHomePhone", txtCustHomePhone.Text);
com.Parameters.AddWithValue("#custBusPhone", txtCustBusPhone.Text);
com.Parameters.AddWithValue("#custEmail", txtCustEmail.Text);
com.Parameters.AddWithValue("#custUsername", txtCustUserName.Text);
com.Parameters.AddWithValue("#custPassword", txtCustPassword.Text);
com.ExecuteNonQuery();
Response.Redirect("Manager.aspx");
Response.Write("Registration is successful" );
conn.Close();
}
catch(Exception ex)
{
Response.Write("Error:"+ex.ToString());
}
}
}
The login page marks all logins as "wrong username" even though the username and password are correct.
This is the 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;
using System.Configuration;
public partial class Login : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
this.UnobtrusiveValidationMode = System.Web.UI.UnobtrusiveValidationMode.None;
}
protected void btnLogin_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["RegistrationDatabaseConnectionString"].ConnectionString);
conn.Open();
string checkuser = "SELECT count(*) FROM Customers WHERE CustUserName='" + txtUsername.Text + "'";
SqlCommand com = new SqlCommand(checkuser, conn);
int temp = Convert.ToInt32(com.ExecuteScalar().ToString());
conn.Close();
if (temp > 0)
{
conn.Open();
string checkPasswordQuery= "SELECT password FROM Customers WHERE CustUserName='" + txtUsername.Text + "'";
SqlCommand passCom = new SqlCommand(checkPasswordQuery, conn);
string password = passCom.ExecuteScalar().ToString().Replace(" ","");
if(password == txtPassword.Text)
{
Session["New"] = txtUsername.Text;
Response.Write("Password is correct");
Response.Redirect("Manager.aspx");
}
else
{
Response.Write("Password is not correct");
}
}
else
{
Response.Write("Username is not correct");
}
}
}
Thank you.
What is the value of temp here during debugging?:
int temp = Convert.ToInt32(com.ExecuteScalar().ToString());
If you have duplicate records in your table, the variable temp will never be 1.
Set CustUserName as a primary key on your Customers table to prevent duplicate entry.
Please try this.
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;
using System.Configuration;
public partial class Registration : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
this.UnobtrusiveValidationMode = System.Web.UI.UnobtrusiveValidationMode.None;
if (!IsPostBack)
{
}
}
protected void Button1_Click(object sender, EventArgs e)
{
try
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["RegistrationDatabaseConnectionString"].ConnectionString);
conn.Open();
string checkuser = "SELECT count(*) FROM Customers WHERE CustUserName='" + txtCustUserName.Text + "'";
SqlCommand com = new SqlCommand(checkuser, conn);
int temp = Convert.ToInt32(com.ExecuteScalar().ToString());
conn.Close();
if (temp > 0)
{
Response.Write("User already exists");
}
else
{
conn.Open();
string insertQuery = "INSERT into Customers (CustFirstName, CustLastName, CustAddress, CustCity, CustProv, CustPostal, CustCountry, CustHomePhone, CustBusPhone, CustEmail, CustUserName, CustPassword) values (#custFirstName ,#custLastName ,#custAddress ,#custCity ,#custProv ,#custPostal, #custCountry ,#custHomePhone ,#custBusPhone ,#custEmail ,#custUserName ,#custPassword)";
SqlCommand com = new SqlCommand(insertQuery, conn);
com.Parameters.AddWithValue("#custFirstName", txtCustFirstName.Text);
com.Parameters.AddWithValue("#custLastName", txtCustLastName.Text);
com.Parameters.AddWithValue("#custAddress", txtCustAddress.Text);
com.Parameters.AddWithValue("#custCity", txtCustCity.Text);
com.Parameters.AddWithValue("#custProv", txtCustProv.Text);
com.Parameters.AddWithValue("#custPostal", txtCustPostal.Text);
com.Parameters.AddWithValue("#custCountry", txtCustCountry.Text);
com.Parameters.AddWithValue("#custHomePhone", txtCustHomePhone.Text);
com.Parameters.AddWithValue("#custBusPhone", txtCustBusPhone.Text);
com.Parameters.AddWithValue("#custEmail", txtCustEmail.Text);
com.Parameters.AddWithValue("#custUsername", txtCustUserName.Text);
com.Parameters.AddWithValue("#custPassword", txtCustPassword.Text);
com.ExecuteNonQuery();
Response.Redirect("Manager.aspx");
Response.Write("Registration is successful" );
conn.Close();
}
}
catch(Exception ex)
{
Response.Write("Error:"+ex.ToString());
}
}
}
I'm not really sure where the SqlConnection, SqlCommand and the Open()/Close() goes. I want to use just the single variable cmd throughout the program, hence not using the SqlCommand cmd = new SqlCommand('SELCT * FROM blabla); format.
EDIT: My code below results to the textbox having the text "System.Data.SqlClient.SqlCommand" when i click the button.
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 System.Data.SqlClient;
using System.Data.SqlTypes;
namespace WindowsFormsApplication2
{
public partial class Form1 : Form
{
SqlConnection con = new SqlConnection(#"Data Source=EDIOTH\SQLEXPRESS;
Initial Catalog=Try; Integrated Security=SSPI");
SqlCommand cmd = new SqlCommand();
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
con.Open();
cmd.CommandText = "SELECT Pnt_Lname FROM PATIENT WHERE Pnt_ID = 1;";
txtBox1.Text = cmd.ToString();
con.Close();
}
}
}
you can create constant string to hold the connection string and then you can do as below in your button1_Click
you don't need to call the close method of sql connection when you use using block as below
using(SqlConnection con = new SqlConnection(connectionString))
using(SqlCommand cmd = con.CreateCommand())
{
cmd.CommandText = "SELECT Pnt_Lname FROM PATIENT WHERE Pnt_ID = 1";
con.Open();
txtBox1.Text =cmd.ExecuteScalar() as string;
}
And also if you need to read Pnt_Lname from database you better use ExecuteScalar method
You can use this structure. Use using to properly close and dispose of SqlConnection.
Also, you can define the connection string in your config file and use it from there.
using (SqlConnection conn = new SqlConnection(#"Data Source=EDIOTH\SQLEXPRESS;
Initial Catalog=Try; Integrated Security=SSPI"))
{
conn.Open();
SqlCommand command = conn.CreateCommand();
command.CommandText = "SELECT Pnt_Lname FROM PATIENT WHERE Pnt_ID = 1";
txtBox1.Text = (String)command.ExecuteScalar();
}
In case this would be of help to anyone, this is the answer to my question:
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 System.Data.SqlClient;
namespace Book
{
public partial class frmBook : Form
{
SqlConnection con =
new SqlConnection(#"Data Source=EDIOTH\SQLEXPRESS;
Initial Catalog=XXDB; Integrated Security=SSPI");
SqlCommand cmd;
public frmBook()
{
InitializeComponent();
}
private void frmBook_Load(object sender, EventArgs e)
{
con.Open();
cmd = new SqlCommand("SELECT min(Book_ID) FROM Book;",con);
txtID.Text = cmd.ExecuteScalar().ToString();
cmd = new SqlCommand("SELECT title FROM Book WHERE Book_ID = '"
+ txtID.Text + "'", con);
txtTitle.Text = cmd.ExecuteScalar().ToString();
con.Close();
btnSave.Enabled = false;
}
private void btnNext_Click(object sender, EventArgs e)
{
int count = int.Parse(txtID.Text) + 1;
con.Open();
cmd = new SqlCommand("SELECT title FROM Book WHERE Book_ID = '"
+ count.ToString() +"'", con);
txtTitle.Text = cmd.ExecuteScalar().ToString();
txtID.Text = count.ToString();
con.Close();
}
private void btnNew_Click(object sender, EventArgs e)
{
txtID.Text = "";
txtTitle.Text = "";
txtAuthor.Text = "";
btnNew.Enabled = false;
btnSave.Enabled = true;
}
private void btnSave_Click(object sender, EventArgs e)
{
con.Open();
cmd = new SqlCommand("INSERT INTO Book (Book_ID, Title, Author) " +
"VALUES ('"+ txtID.Text +
"','"+ txtTitle.Text +
"','"+ txtAuthor.Text +"');", con);
cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show("Data saved!");
btnSave.Enabled = false;
}
private void btnClose_Click(object sender, EventArgs e)
{
this.Close();
}
}
}
I am trying to insert data from text box to sql database, but I want to check if the row is empty then insert new value else update the row with the values with sqlcommands in if else condition.
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;
using System.Data.SqlClient;
public partial class CM : System.Web.UI.Page
{
DataSet ds = new DataSet();
SqlDataAdapter da;
SqlCommand cmd;
//DataTable dt;
SqlConnection con = new SqlConnection("server =consulting76\\SQLEXPRESS; database = msdb; Integrated Security=True");
protected void Page_Load(object sender, EventArgs e)
{
da = new SqlDataAdapter();
//("Select * from NOTESMAKER", con);
//da.Fill(ds, "NOTESMAKER");
//dt = ds.Tables["NOTESMAKER"];
}
protected void Button1_Click(object sender, EventArgs e)
{
con.Open();
if (DBNull.Value != null)
{
cmd = new SqlCommand("Insert into NOTESMAKER(NOTESMAKER) Values(#text1)",con);
cmd.Parameters.Add(new SqlParameter("#text1", SqlDbType.NText)).Value = TextBox1.Text;
da.InsertCommand = cmd;
cmd.ExecuteNonQuery();
}
else
{
cmd = new SqlCommand("Update NOTESMAKER set NOTESMAKER = #text1)",con);
cmd.Parameters.Add(new SqlParameter("#text1", SqlDbType.NText)).Value = TextBox1.Text;
da.UpdateCommand = cmd;
cmd.ExecuteNonQuery();
}
con.Close();
}
}
if you don't know how to fired a select query, have a look here
select * from tablename where columnName is not null
fill sqldataadapter from your query eg
if dataset count is zero then you may proceed with insert operation else update.
if (ds.table[0].rows.count==0)//insert
{
}
else// update
}
You can do it this way. ExecuteNonQuery() returns the number of affected rows, so if insert returns 0, it means that there was nothing to update. Hence you need to insert a row.
cmd = new SqlCommand("Update NOTESMAKER set NOTESMAKER = #text1)",con);
cmd.Parameters.Add(new SqlParameter("#text1", SqlDbType.NText)).Value = TextBox1.Text;
int affectedRows = cmd.ExecuteNonQuery();
if (affectedRows == 0)
{
cmd = new SqlCommand("Insert into NOTESMAKER(NOTESMAKER) Values(#text1)",con);
cmd.Parameters.Add(new SqlParameter("#text1", SqlDbType.NText)).Value = TextBox1.Text;
cmd.ExecuteNonQuery();
}
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();