I am trying to store the username and password inside a table called 'User' which is inside a service-based database.
Below is code of what i have tried.
private void Btn_register_Click(object sender, RoutedEventArgs e)
{
try
{
//Create the conection string and open the conn
SqlConnection conne = new SqlConnection(#"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=\\CUC-SRV-FS02\Studio-StuHome$\13mihailovs.m\Documents\IT_Unit4\IT_Unit4\ITUnit4.mdf;Integrated Security=True");
//Open the connection string
conne.Open();
//Get all the values from the text boxes etc and pass them over to the DB
string insertQuery = "insert into User(Username, Password) " +
"values(#Username, #Password)";
SqlCommand com = new SqlCommand(insertQuery, conne);
//Get values from the controls such as the text boxes and pass them over to the DB
com.Parameters.AddWithValue("#Username", txt_username.Text);
com.Parameters.AddWithValue("#Password", txt_password.Text);
//This actually executes the query with the given values above.
com.ExecuteNonQuery();
//Dispose the connection string once the data has been passed over the DB
conne.Close();
}
catch (Exception problem)
{
MessageBox.Show("error has occured");
}
}
currect way for insert into database in Ado.Net:
private readonly SqlConnection _con = new SqlConnection("Data Source=.;Initial
Catalog=dbPhoneBook;Integrated Security=True");
public string Add(string user , string pass)
{
string result = "";
SqlCommand cmd = new SqlCommand();
try
{
cmd.Connection = _con;
cmd.CommandText = "insert into tbl_login(user,pass)values(#user,#pass)";
cmd.Parameters.AddWithValue("#user", user);
cmd.Parameters.AddWithValue("#pass", pass);
if (_con.State != ConnectionState.Open)
{
_con.Open();
}
cmd.ExecuteNonQuery();
result = "Ok";
cmd.Dispose();
}
catch
{
cmd.Dispose();
result = "NOk";
}
return result;
}
Also check the following
Check out the web site https://www.connectionstrings.com/ link to the database.
Trying to update the first name of the student there is a textbox "FirstNameTextbox" information was loaded to it from the DB, when I change the information in the textbox and try to write the changes it read only the original data.So if it loaded "Craig" as the first name from the DB, i would edit and put "Chris" in the textbox, what happens is that Craig is written to the DB and not "Chris"
int stuID = getSqlStuID(IDNUMLabel.Text);
SqlConnection conn = new SqlConnection(GetConnectionString());
string sqlUpdateStudent = "Update tblStudent set fname = #fname where stuID = #stuID";
SqlCommand cmd = new SqlCommand(sqlUpdateStudent, conn);
conn.Open();
cmd.Parameters.AddWithValue("#stuID", stuID);
cmd.Parameters.AddWithValue("#fname", FirstNameTextbox.Text);
cmd.ExecuteNonQuery();
ErrorMessage.Text = "Success";
protected void Page_Load(object sender, EventArgs e)
{
if (Session["User"] != null)
{
IDNUMLabel.Text = Session["User"].ToString();
getStuData(Session["User"].ToString());
}
else
{
Response.Redirect("../Login/Login.aspx");
}
}
private void getStuData(string id)
{
SqlConnection conn = new SqlConnection(GetConnectionString());
string sql = "Select fname, sname From tblStudent Where idnumber = '" + id + "' ";
SqlCommand cmd = new SqlCommand(sql, conn);
try
{
conn.Open();
SqlDataReader selectedRecord = cmd.ExecuteReader();
cmd.CommandType = CommandType.Text;
while (selectedRecord.Read())
{
FirstNameTextbox.Text = selectedRecord["fname"].ToString();
LastNameTextbox.Text = selectedRecord["sname"].ToString();
}
selectedRecord.Close();
}
catch (System.Data.SqlClient.SqlException ex)
{
//id = 0;
//string msg = "Error reading Student ID";
//msg += ex.Message;
//throw new Exception(msg);
}
catch (Exception ex)
{
}
finally
{
conn.Close();
}
}
At what point do you make the actual update? After a button was pressed, after the value was entered on the textbox...? You're missing the method in which the code that handles the update is placed...
Maybe this could help: How to display data from database into textbox, and update it
I want to change password that saved in db,but my code dose not work. what is wrong? I always see the last message:
unable to connect database
public partial class pws : System.Web.UI.Page
{
static string strcon = (System.Web.Configuration.WebConfigurationManager.ConnectionStrings["strcon"].ConnectionString);
protected void Page_Load(object sender, EventArgs e)
{
}
private void ShowPopUpMsg(string msg)
{
StringBuilder sb = new StringBuilder();
sb.Append("alert('");
sb.Append(msg.Replace("\n", "\\n").Replace("\r", "").Replace("'", "\\'"));
sb.Append("');");
ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "showalert", sb.ToString(), true);
}
protected void btnInsert_Click(object sender, EventArgs e)
{
try {
SqlConnection db = new SqlConnection(strcon);
db.Open();
string strId = string.Empty;
string strusername = string.Empty;
string OLdpassword = string.Empty;
SqlCommand cmd;
cmd = new SqlCommand("SELECT * FROM login WHERE login_username =#login_username ", db);
cmd.Parameters.AddWithValue("login_username", txtOldUsername.Text);
cmd.ExecuteNonQuery();
cmd.Parameters.Clear();
cmd.Dispose();
cmd = null;
db.Close();
db.Open();
SqlDataReader DR;
DR = cmd.ExecuteReader();
if (DR.Read())
{
strId = DR["login_id"].ToString();
strusername = DR["login_username"].ToString();
OLdpassword = DR["login_Password"].ToString();
}
db.Close();
if (OLdpassword == txtOldPass.Text)
{
db.Open();
string Command = "Update login Set login_Password= #login_Password WHERE login_username=#login_username";
SqlCommand cmdIns = new SqlCommand(Command, db);
cmdIns.Parameters.AddWithValue("#login_Password ", txtNewPass.Text);
cmdIns.Parameters.AddWithValue("#login_username ", txtOldUsername.Text);
cmdIns.ExecuteNonQuery();
cmdIns.Parameters.Clear();
cmdIns.Dispose();
cmdIns = null;
db.Close();
ShowPopUpMsg("successful");
}
else
{
ShowPopUpMsg(" old pass is not correct");
}
}
catch
{
ShowPopUpMsg("unable to connect database");
}
}
}
this part:
cmd.ExecuteNonQuery();
cmd.Parameters.Clear();
cmd.Dispose();
cmd = null;
db.Close();
db.Open();
SqlDataReader DR;
DR = cmd.ExecuteReader();
why do you execute a non query, which is a query (select * from ...)?
why do you dispose the SqlCommand object cmd and why do you reuse it after disposing?
why do you close and open the line below?
I would rewrite those lines it like this:
SqlDataReader DR = cmd.ExecuteReader();
I would recomment a using statement or closing the connection in a finally block:
SqlConnection db = new SqlConnection(strcon);
try{
db.Open();
//.... the rest
}
catch(Exception ex)
{
ShowPopUpMsg("unable to connect database: " + ex.Message);
}
finally
{
db.Close();
}
and another thing: I would use the primary key in the update statement. where id = login_id instead of the username. unless the username is set to "unique"
Check if you can connect to the database using your credentials and database management tool (I assume you you use MS SQL Server so use MS SQL Server Management Studio)
Check if the format of your connection string is correct. You can use this website http://www.connectionstrings.com/ to do it.
I hope this will help you.
Try to step through the code and find where the exception occures, and look at the details of the exception.
My guess is that there are something wrong with you connection string (strcon).
I'm having an issue at the moment which I am trying to fix. I just tried to access a database and insert some values with the help of C#
The things I tried (worked)
String query = "INSERT INTO dbo.SMS_PW (id,username,password,email) VALUES ('abc', 'abc', 'abc', 'abc')";
A new line was inserted and everything worked fine, now I tried to insert a row using variables:
String query = "INSERT INTO dbo.SMS_PW (id,username,password,email) VALUES (#id, #username, #password, #email)";
command.Parameters.AddWithValue("#id","abc")
command.Parameters.AddWithValue("#username","abc")
command.Parameters.AddWithValue("#password","abc")
command.Parameters.AddWithValue("#email","abc")
command.ExecuteNonQuery();
Didn't work, no values were inserted. I tried one more thing
command.Parameters.AddWithValue("#id", SqlDbType.NChar);
command.Parameters["#id"].Value = "abc";
command.Parameters.AddWithValue("#username", SqlDbType.NChar);
command.Parameters["#username"].Value = "abc";
command.Parameters.AddWithValue("#password", SqlDbType.NChar);
command.Parameters["#password"].Value = "abc";
command.Parameters.AddWithValue("#email", SqlDbType.NChar);
command.Parameters["#email"].Value = "abc";
command.ExecuteNonQuery();
May anyone tell me what I am doing wrong?
Kind regards
EDIT:
in one other line I was creating a new SQL-Command
var cmd = new SqlCommand(query, connection);
Still not working and I can't find anything wrong in the code above.
I assume you have a connection to your database and you can not do the insert parameters using c #.
You are not adding the parameters in your query. It should look like:
String query = "INSERT INTO dbo.SMS_PW (id,username,password,email) VALUES (#id,#username,#password, #email)";
SqlCommand command = new SqlCommand(query, db.Connection);
command.Parameters.Add("#id","abc");
command.Parameters.Add("#username","abc");
command.Parameters.Add("#password","abc");
command.Parameters.Add("#email","abc");
command.ExecuteNonQuery();
Updated:
using(SqlConnection connection = new SqlConnection(_connectionString))
{
String query = "INSERT INTO dbo.SMS_PW (id,username,password,email) VALUES (#id,#username,#password, #email)";
using(SqlCommand command = new SqlCommand(query, connection))
{
command.Parameters.AddWithValue("#id", "abc");
command.Parameters.AddWithValue("#username", "abc");
command.Parameters.AddWithValue("#password", "abc");
command.Parameters.AddWithValue("#email", "abc");
connection.Open();
int result = command.ExecuteNonQuery();
// Check Error
if(result < 0)
Console.WriteLine("Error inserting data into Database!");
}
}
Try
String query = "INSERT INTO dbo.SMS_PW (id,username,password,email) VALUES (#id,#username, #password, #email)";
using(SqlConnection connection = new SqlConnection(connectionString))
using(SqlCommand command = new SqlCommand(query, connection))
{
//a shorter syntax to adding parameters
command.Parameters.Add("#id", SqlDbType.NChar).Value = "abc";
command.Parameters.Add("#username", SqlDbType.NChar).Value = "abc";
//a longer syntax for adding parameters
command.Parameters.Add("#password", SqlDbType.NChar).Value = "abc";
command.Parameters.Add("#email", SqlDbType.NChar).Value = "abc";
//make sure you open and close(after executing) the connection
connection.Open();
command.ExecuteNonQuery();
}
The most common mistake (especially when using express) to the "my insert didn't happen" is : looking in the wrong file.
If you are using file-based express (rather than strongly attached), then the file in your project folder (say, c:\dev\myproject\mydb.mbd) is not the file that is used in your program. When you build, that file is copied - for example to c:\dev\myproject\bin\debug\mydb.mbd; your program executes in the context of c:\dev\myproject\bin\debug\, and so it is here that you need to look to see if the edit actually happened. To check for sure: query for the data inside the application (after inserting it).
static SqlConnection myConnection;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
myConnection = new SqlConnection("server=localhost;" +
"Trusted_Connection=true;" +
"database=zxc; " +
"connection timeout=30");
try
{
myConnection.Open();
label1.Text = "connect successful";
}
catch (SqlException ex)
{
label1.Text = "connect fail";
MessageBox.Show(ex.Message);
}
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void button2_Click(object sender, EventArgs e)
{
String st = "INSERT INTO supplier(supplier_id, supplier_name)VALUES(" + textBox1.Text + ", " + textBox2.Text + ")";
SqlCommand sqlcom = new SqlCommand(st, myConnection);
try
{
sqlcom.ExecuteNonQuery();
MessageBox.Show("insert successful");
}
catch (SqlException ex)
{
MessageBox.Show(ex.Message);
}
}
private void button1_Click(object sender, EventArgs e)
{
String query = "INSERT INTO product (productid, productname,productdesc,productqty) VALUES (#txtitemid,#txtitemname,#txtitemdesc,#txtitemqty)";
try
{
using (SqlCommand command = new SqlCommand(query, con))
{
command.Parameters.AddWithValue("#txtitemid", txtitemid.Text);
command.Parameters.AddWithValue("#txtitemname", txtitemname.Text);
command.Parameters.AddWithValue("#txtitemdesc", txtitemdesc.Text);
command.Parameters.AddWithValue("#txtitemqty", txtitemqty.Text);
con.Open();
int result = command.ExecuteNonQuery();
// Check Error
if (result < 0)
MessageBox.Show("Error");
MessageBox.Show("Record...!", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information);
con.Close();
loader();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
con.Close();
}
}
public static string textDataSource = "Data Source=localhost;Initial
Catalog=TEST_C;User ID=sa;Password=P#ssw0rd";
public static bool ExtSql(string sql) {
SqlConnection cnn;
SqlCommand cmd;
cnn = new SqlConnection(textDataSource);
cmd = new SqlCommand(sql, cnn);
try {
cnn.Open();
cmd.ExecuteNonQuery();
cnn.Close();
return true;
}
catch (Exception) {
return false;
}
finally {
cmd.Dispose();
cnn = null;
cmd = null;
}
}
I have just wrote a reusable method for that, there is no answer here with reusable method so why not to share...here is the code from my current project:
public static int ParametersCommand(string query,List<SqlParameter> parameters)
{
SqlConnection connection = new SqlConnection(ConnectionString);
try
{
using (SqlCommand cmd = new SqlCommand(query, connection))
{ // for cases where no parameters needed
if (parameters != null)
{
cmd.Parameters.AddRange(parameters.ToArray());
}
connection.Open();
int result = cmd.ExecuteNonQuery();
return result;
}
}
catch (Exception ex)
{
AddEventToEventLogTable("ERROR in DAL.DataBase.ParametersCommand() method: " + ex.Message, 1);
return 0;
throw;
}
finally
{
CloseConnection(ref connection);
}
}
private static void CloseConnection(ref SqlConnection conn)
{
if (conn.State != ConnectionState.Closed)
{
conn.Close();
conn.Dispose();
}
}
class Program
{
static void Main(string[] args)
{
string connetionString = null;
SqlConnection connection;
SqlCommand command;
string sql = null;
connetionString = "Data Source=Server Name;Initial Catalog=DataBaseName;User ID=UserID;Password=Password";
sql = "INSERT INTO LoanRequest(idLoanRequest,RequestDate,Pickupdate,ReturnDate,EventDescription,LocationOfEvent,ApprovalComments,Quantity,Approved,EquipmentAvailable,ModifyRequest,Equipment,Requester)VALUES('5','2016-1-1','2016-2-2','2016-3-3','DescP','Loca1','Appcoment','2','true','true','true','4','5')";
connection = new SqlConnection(connetionString);
try
{
connection.Open();
Console.WriteLine(" Connection Opened ");
command = new SqlCommand(sql, connection);
SqlDataReader dr1 = command.ExecuteReader();
connection.Close();
}
catch (Exception ex)
{
Console.WriteLine("Can not open connection ! ");
}
}
}
I want to Check the "refno" already present in Tbldelivery table, If "refno" is present, then it will insert in "Tbldeliverydetails" because "refno" is primary key in 1st table. Where i check the condition ?
Here is the code i wrote in C# :
protected void btndlysave_Click(object sender, EventArgs e)
{
SqlConnection SqlCon = new SqlConnection("server=(local);Initial Catalog=TestDB;Integrated Security=SSPI;");
try
{
SqlCon.Open();
SqlCommand cmd = new SqlCommand("insert into Tbldelivery (refno,deliverdate,requestby,projectcode) values
(#refno,#deliverdate,#requestby,#projectcode) WHERE not exists (select refno from Tblinkdelivery where refno = #refno)", SqlCon);
cmd.CommandType = CommandType.Text;
if ( need check here)
cmd.Parameters.AddWithValue("#refno", txtdelrefno.Text.Trim());
cmd.Parameters.AddWithValue("#deliverdate", txtdeldate.Text.Trim());
cmd.Parameters.AddWithValue("#requestby", txtdelreq.Text.Trim());
cmd.Parameters.AddWithValue("#projectcode", ddlprojcode.Text.Trim());
}
else
{
SqlCommand cmd2 = new SqlCommand("insert into Tbldeliverdetails (refno,printercode,inkcode,quantity,price,notes) values (#refno,#printercode,#inkcode,#quantity,#price,#notes)", SqlCon);
cmd2.CommandType = CommandType.Text;
cmd2.Parameters.AddWithValue("#refno", txtdelrefno.Text.Trim());
cmd2.Parameters.AddWithValue("#printercode", ddldelprcode.Text.Trim());
cmd2.Parameters.AddWithValue("#inkcode", ddlinkcode.Text.Trim());
cmd2.Parameters.AddWithValue("#quantity", txtdelqty.Text.Trim());
cmd2.Parameters.AddWithValue("#price", txtdelprice.Text.Trim());
cmd2.Parameters.AddWithValue("#notes", txtdelnotes.Text.Trim());
int val1 = cmd.ExecuteNonQuery();
int val2 = cmd2.ExecuteNonQuery();
}
finally
{
SqlCon.Close();
}
}
I think first of all you need to arrange your code.
Writing everything inside the button click event is not good at all. It is better if you can separate business logic and put it separately.
Try something like this.
You can create Data Access class which handle your data access.
In your Data Access Class
public SqlConnection OpenConnection()
{
try
{
var conn = new SqlConnection(“xxx”);
conn.Open();
return conn;
}
catch (Exception ex)
{
//log the exception
return null;
}
}
YourFunction(parameters)
{
var conn = OpenConnection();
if(conn != null)
{
//your code
// you can do something similar as JeremyK explained here
}
}
And in your button click
protected void btndlysave_Click(object sender, EventArgs e)
{
//CHECK THE PARAMETERS AND PASS
//DataAccess. YourFunction(parameters)
}
You query the table and see if it exists.
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
SqlCommand sqlCommand =
new SqlCommand("SELECT * FROM dbo.Tbldelivery WHERE refno=#refno",
connection);
sqlCommand.Parameters.Add("#refno", System.Data.SqlDbType.VarChar);
sqlCommand.Parameters["#refno"].Value = refnoValue;
SqlDataReader reader = sqlCommand.ExecuteReader();
reader.Read();
if (reader.HasRows)
{
// refno exists
}
else
{
// refno does not exist
}
}