ASP.net form SQL Server update from inputbox - c#

I'm trying to update a table in my SQL Server database with text from an input box on my site;
My table is MemberSite.dbo.Users and the columns within this table are:
ID (Auto incrementing) UserName, Password, ApiKey, VeriF
It's not updating my SQL Server table.
What I want this to do: take the input text and put it in my SQL Server table against the user that is logged in.
Here is some code web.config :
<add name="WRITER"
connectionString="Data Source=localhost;Initial Catalog=MembershipSite;User ID=test;Password=test!"
providerName="System.Data.SqlClient" />
Backend to button click;
protected void Save_Click(object sender, EventArgs e)
{
SqlConnection conn = null;
try
{
string sql = "UPDATE dbo.Users SET ApiKey = #API, VeriF = #verif WHERE UserName = #username";
conn = new SqlConnection(ConfigurationManager.ConnectionStrings["WRITER"].ConnectionString);
SqlCommand cmd = new SqlCommand(sql, conn);
SqlParameter api = new SqlParameter();
api.ParameterName = "#API";
api.Value = APIinput;
cmd.Parameters.Add(api);
SqlParameter verif = new SqlParameter();
verif.ParameterName = "#verif";
verif.Value = Veri;
cmd.Parameters.Add(verif);
SqlParameter UserN = new SqlParameter();
UserN.ParameterName = "#username";
UserN.Value = User.Identity.Name;
cmd.Parameters.Add(UserN);
conn.Open();
}
finally
{
if (conn !=null)
conn.Close();
}
}

Because you never execute your command. Just add:
cmd.ExecuteNonQuery();
after you open your connection.
Also use using statement to dispose your connection and command automatically instead of calling Close or Dispose methods manually. Like;
using(var conn = new SqlConnection(conString))
using(var cmd = conn.CreateCommand())
{
// Set your CommandText
// Add your parameters
// Open your connection
// Execute your command.
}

You have missed cmd.ExecuteNonQuery() after connection.Open(). That's why the values are not updated

Related

TSQL logging inside transaction using CLR stored procedure

I'm trying to write a log into another database inside a transaction so that the log will survive even if the transaction is rolled back. I've read this answer which says:
One possibility is to use a CLR stored procedure to do the logging. This can open its own connection to the database outside the transaction and enter and commit the log data.
So I created CLR stored procedure using this article:
[SqlProcedure]
public static void Voice(SqlString procedureName, SqlInt32 id)
{
Connection = new SqlConnectionStringBuilder();
Connection.ContextConnection = true;
using (TransactionScope transScope = new TransactionScope())
{
using (SqlConnection conn = new SqlConnection(Connection.ToString()))
{
conn.Open();
SqlCommand cmdInsert = conn.CreateCommand();
cmdInsert.CommandText = sql;
cmdInsert.Parameters.Add("#id", SqlDbType.Int);
cmdInsert.Parameters[0].Value = id;
cmdInsert.Parameters.Add("#procedureName", SqlDbType.NVarChar);
cmdInsert.Parameters[1].Value = procedureName;
cmdInsert.ExecuteNonQuery();
}
transScope.Complete();
}
}
However, data is not saved afer I executed and rolled back stored procedure in SQL Server:
BEGIN TRAN
EXEC dbo.SayHelloVoice #id = 1,
#procedureName = N'FooProcedure'
ROLLBACK TRAN
We have three environments:
dev. Server name is Q-SQL001
test. Server name is Q-SQL002
prod. Server name is Q-SQL003
So this CLR stored procedure should work on all environments.
Could you say what I am doing wrong?
Any help would be greatly appreciated!
UPDATE:
So the work version looks like this. Big thanks to the #Milney:
var serverName = string.Empty;
var dbName = string.Empty;
serverName = SqlExecuteScalar("SELECT ##SERVERNAME");
dbName = SqlExecuteScalar("SELECT DB_NAME()");
SqlConnectionStringBuilder sqlConn = new SqlConnectionStringBuilder();
sqlConn.InitialCatalog = dbName;
sqlConn.DataSource = serverName;
sqlConn.IntegratedSecurity = true;
sqlConn.ContextConnection = false;
sqlConn.Enlist = false;
sqlConn.ApplicationName = "New application";
var sql = "USE FooDatabase
INSERT INTO dbo.MyTable ..."
using (SqlConnection conn2 = new SqlConnection(sqlConn.ConnectionString))
{
conn2.Open();
SqlCommand cmdInsert = conn2.CreateCommand();
cmdInsert.CommandText = sql;
cmdInsert.Parameters.Add("#id", SqlDbType.Int);
cmdInsert.Parameters[0].Value = storeTime;
cmdInsert.Parameters.Add("#messageText", SqlDbType.NVarChar);
cmdInsert.Parameters[1].Value = messageText;
cmdInsert.ExecuteNonQuery();
}
If you use:
Connection.ContextConnection = true;
Then it's going to use the same connection that the CLR Sproc is running in - you need to open a new connection.

Delete a record from database

I'm trying to delete record from data base MSSQL by entering the ID and hit delete btn. i didn't get any error and it give recorded deleted successful but once i check database i see the record doesn't deleted
protected void btnDelete_Click(object sender, EventArgs e)
{
try
{
if (txtImgID.Text == "")
{
Response.Write("Enter Image Id To Delete");
}
else
{
SqlCommand cmd = new SqlCommand();
SqlConnection con = new SqlConnection();
con = new SqlConnection(ConfigurationManager.ConnectionStrings["GMSConnectionString"].ConnectionString);
con.Open();
cmd = new SqlCommand("delete from certf where id=" + txtImgID.Text + "", con);
lblsubmitt.Text = "Data Deleted Sucessfully";
}
}
catch (Exception)
{
lblsubmitt.Text = "You haven't Submited any data";
}
}
var idToDelete = int.Parse(txtImgID.Text); // this is not necessary if the data type in the DB is actually a string
using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["GMSConnectionString"].ConnectionString))
using (SqlCommand cmd = new SqlCommand("DELETE FROM [certf] WHERE id = #id", con))
{
// I am assuming that id is an integer but if it is a varchar/string then use the line below this one
// cmd.Parameters.Add("#id", SqlDbType.VarChar, 100).Value = txtImgID.Text;
cmd.Parameters.Add("#id", SqlDbType.Int32).Value = idToDelete;
cmd.ExecuteNonQuery();
}
You need to call ExecuteNonQuery which executes the query against the database.
Always use parameters instead of string concatenation in your queries. It guards against sql injection and ensures you never has issues with strings that contain escape characters.
I did not include any error handling or return messages but do note that you are throwing away all the good stuff in your excetion handler's catch block, you will never know why a query failed after this has executed.

can't read int value from sql database

I have tried this code in C#, and it's not working - I can't get an input id, every time I run it, the value of id is 0.
SqlConnection con = new SqlConnection("Data Source=.;Initial Catalog=sms;Persist Security Info=True;User ID=boy;Password=coco");
int id;
con.Open();
string sql = "select * from Staff_Management where Emp_Name = '"+sName+"'; ";
SqlCommand cmd = new SqlCommand(sql, con);
SqlDataReader read = cmd.ExecuteReader();
if (read.Read())
{
id = read.GetInt32(0);
TM_AC_SelectId.Text = id.ToString();
}
else
{
MessageBox.Show("Error 009 ");
}
con.Close();
You should try to follow the accepted best practices for ADO.NET programming:
use parameters for your query - always - no exceptions
use the using(...) { .... } construct to ensure proper and quick disposal of your resources
select really only those columns that you need - don't just use SELECT * out of lazyness - specify your columns that you really need!
Change your code to this:
// define connection string (typically loaded from config) and query as strings
string connString = "Data Source=.;Initial Catalog=sms;Persist Security Info=True;User ID=boy;Password=coco";
string query = "SELECT id FROM dbo.Staff_Management WHERE Emp_Name = #EmpName;";
// define SQL connection and command in "using" blocks
using (SqlConnection con = new SqlConnection(connString))
using (SqlCommand cmd = new SqlCommand(query, con))
{
// set the parameter value
cmd.Parameter.Add("#EmpName", SqlDbType.VarChar, 100).Value = sName;
// open connection, execute scalar, close connection
con.Open();
object result = cmd.ExecuteScalar();
con.Close();
int id;
if(result != null)
{
if (int.TryParse(result.ToString(), out id)
{
// do whatever when the "id" is properly found
}
}
}

C# Connection must be valid and open Mysql

is there something wrong with my codes. I already try another codes but the problem is still the same. I've been solving this error for a couple of weeks now, and i can't figure it out how to solve it. And also I already try some another code but the problem is still the same.
I want to save a multiple row from dataGrid to my database.
here's the codes that i use to save a multiple row
private void button1_Click(object sender, EventArgs e)
{
MySqlConnection conString = new MySqlConnection("datasource = localhost; port = 3306; Initial catalog = dbnewsystem; username = root;password = 1234");
MySqlCommand command1 = new MySqlCommand("INSERT INTO purchaseorder (orNo, ProdNo, Quantity, total)" +
"VALUES(#ORNo,#ProductNo,#quantity,#total )", conString);
command1.Parameters.AddWithValue("#ORNo", dataGridView1.Rows.Count);
command1.Parameters.AddWithValue("#ProductNo", dataGridView1.Rows.Count);
command1.Parameters.AddWithValue("#quantity", dataGridView1.Rows.Count);
command1.Parameters.AddWithValue("#total", textBox6.Text);
conString.Open();
command1.ExecuteNonQuery();
command1.Connection = conString;
conString.Close();
command1.CommandType = CommandType.StoredProcedure;
command1.CommandText = "pos_save";
if (command1.ExecuteNonQuery() == 1)
{
MessageBox.Show("saved");
}
else
{
MessageBox.Show("Sorry Nothing to be Update");
}
conString.Close();
}
change sequence
command1.Connection = conString;
command1.ExecuteNonQuery();
You have implemented wrong sequence:
...
conString.Open(); // Connection opened
command1.ExecuteNonQuery(); // Try executing (fail)
command1.Connection = conString; // Connection assigned
Change to
conString.Open(); // Connection opened
command1.Connection = conString; // Connection assigned
command1.ExecuteNonQuery(); // Try executing (fail)
A better design is
// Wrap IDisposable into using
using (MySqlConnection conString = new MySqlConnection("...")) {
conString.Open();
// Make SQL Readable
string sql =
#"INSERT INTO purchaseorder(
orNo,
ProdNo,
Quantity,
total)
VALUES(
#ORNo,
#ProductNo,
#quantity,
#total)";
// Wrap IDisposable into using
using (MySqlCommand command1 = new MySqlCommand(sql, conString)) {
command1.Parameters.AddWithValue("#ORNo", dataGridView1.Rows.Count);
command1.Parameters.AddWithValue("#ProductNo", dataGridView1.Rows.Count);
command1.Parameters.AddWithValue("#quantity", dataGridView1.Rows.Count);
command1.Parameters.AddWithValue("#total", textBox6.Text);
command1.ExecuteNonQuery();
}
}

SQL Server within & using stored procedure

Trying to create a asp.net c# form for learning purposes at home and i'm absolutely struggling to connect to my storedprocedure.
I'm definitely in the right database as when I start the database by cmdprompt and connect to it via datasource in visual design it connects and finds the stored procedure. So there must be something I am doing wrong? I've been searching Google for about 30-40 minutes now and everything I've tried hasn't resolved my issue. Any suggestions please?
const string constring = #"Data Source=(localdb)\ProjectsV12;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False";
public static int InsertEnquiry(string Name, string Subject, string Email, string Message, string Phone) {
//default ticketid of 0 which will be changed to -1 if an error or greater than 0 if successful
int TicketID = 0;
if (String.IsNullOrEmpty(Phone)) Phone = "0";
using (var conn = new SqlConnection(constring)) {
//create command
SqlCommand command = new SqlCommand();
//tell the command which connection its using
command.Connection = conn;
//inform command that it is a stored procedure and the name of stored procedure
command.CommandText = "InsertEnquiry";
command.CommandType = CommandType.StoredProcedure;
//add the parameters to the sqlcommand
command.Parameters.Add(new SqlParameter("#Name", SqlDbType.NVarChar)).Value = Name;
command.Parameters.Add(new SqlParameter("#Subject", SqlDbType.NVarChar)).Value = Subject;
command.Parameters.Add(new SqlParameter("#Phone", SqlDbType.NVarChar)).Value = Phone;
command.Parameters.Add(new SqlParameter("#Email", SqlDbType.NVarChar)).Value = Email;
command.Parameters.Add(new SqlParameter("#Message", SqlDbType.NVarChar)).Value = Message;
// try run command and set TicketID to the row inserted into the table.
try {
conn.Open();
//run command
command.ExecuteNonQuery();
//return scope identity of row.
TicketID = (int)command.Parameters["#TicketID"].Value;
}
catch (Exception e) {
//show -1 to state there is an error
TicketID = -1;
}
}
return TicketID;
}
}
1st
I think you are connected to the wrong db, probably you are in master.
Run this piece of code and check the name of the database and see if it's the one that you want.
public static string checkDB()
{
string dbName = "";
using (var conn = new SqlConnection(constring))
{
//create command
SqlCommand command = new SqlCommand();
//tell the command which connection its using
command.Connection = conn;
//inform command that it is a stored procedure and the name of stored procedure
command.CommandText = "select DB_NAME()";
command.CommandType = CommandType.Text;
// try run command and set TicketID to the row inserted into the table.
try
{
conn.Open();
//run command
SqlDataReader reader = command.ExecuteReader();
reader.Read();
dbName = reader[0].ToString();
}
catch (Exception e)
{
}
}
return dbName;
}
2nd
You are trying to get the value from the parameter #TicketID but you didn't specify this parameter as an output parameter.
command.Parameters.Add("#TicketID", SqlDbType.Int).Direction = ParameterDirection.Output;
EDIT1:
This is how do you put the db name in the connection string:
const string constring = #"Data Source=(localdb)\ProjectsV12;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;Initial Catalog=MY_DB_NAME";

Categories