This c# code just doesn't want to change Password on the server (UserID and PW will obviously be a strings for some purpose, but this is just to get it working):
SqlConnection conn = new SqlConnection ("Data Source=ServerIP;Persist Security Info=False;User ID=UserID;Password=UserPW");
SqlCommand cmd = new SqlCommand ("ALTER LOGIN UserID WITH PASSWORD='NewPW' OLD_PASSWORD='UserPW'", conn);
cmd.CommandType = CommandType.Text;
conn.Open();
conn.Close();
Changing Password using the same command ALTER LOGIN UserID WITH PASSWORD='NewPW' OLD_PASSWORD='UserPW' with a Server Management studio works like a charm, so there is no problem within command line or/and permissions for this particular User.
I guess I miss something in Sql Connection line.
Already tried combinations of:
Initial Catalog=master;
Initial Catalog=;
Integrated Security=SSPI;
Persist Security Info=True;
Changing command type, using ExecuteNonQuery();, and many other things, but nothing seems to work.
"Google" doesn't give any valuable result, hopefully I will find my answer here, thanks for taking your time in advance.
Try the following, works a treat for me:
SqlConnection conn = new SqlConnection ("Data Source=ServerIP;Persist Security Info=False;User ID=UserID;Password=UserPW");
SqlCommand cmd = new SqlCommand ("ALTER LOGIN UserID WITH PASSWORD='NewPW' OLD_PASSWORD='UserPW'", conn);
cmd.CommandType = CommandType.Text;
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
You forgot to put cmd.ExecuteNonQuery() after you opened the connection. I just tested this and it successfully changed the password on my local database.
string queryString = #"DECLARE #sql NVARCHAR(500)
SET #sql = 'ALTER LOGIN ' + QuoteName(#loginName) +
' WITH PASSWORD= ' + QuoteName(#password, '''')
EXEC #sql ";
using (var connection = new SqlConnection(connectionString))
{
var command = new SqlCommand(queryString, connection);
command.Parameters.AddWithValue("#loginName", loginName);
command.Parameters.AddWithValue("#password", password);
connection.Open();
command.ExecuteNonQuery()
}
UPDATE
With DDL (data definition language) statements (as ALTER LOGIN) you cannot use parameters directly. That's why I'm using a dynamic SQL.
The QuoteName will do proper quoting in the SQL, simply doubles any [ characters (first call) or ' characters (second call).
Related
I can't get an ASP.NET webform to update a database. I'm trying to edit an existing record in the database. The webform populates the data from the record into the form. The user then changes data and updates the record in the database when the form is submitted.
The problem is that nothing is changed in the database when a modified form is submitted. What am I doing wrong here? The SQL works in MSSQL Management Studio.
Thanks.
private void SaveToDatabase ()
{
using (SqlConnection conn = new SqlConnection (_connectionString_Bluebook))
{
conn.Open ();
string sql = #"update Companies
set CompanyName=#CompanyName, AccountNo=#AccountNo
where AccountNo=" + _accountNo;
using (SqlCommand command = new SqlCommand (sql, conn))
{
command.Parameters.Add (new SqlParameter ("#CompanyName", TextBox_CompanyName.Text));
command.Parameters.Add (new SqlParameter ("#AccountNo", TextBox_Account.Text));
command.ExecuteNonQuery ();
}
conn.Close ();
}
}
Try adding a parameter for the original account number to your query. The example below uses strongly-typed parameters for security and performance, taking a guess at your actual SQL data types and column lengths, which you should change to your actual definitions.
private void SaveToDatabase()
{
using (SqlConnection conn = new SqlConnection(_connectionString_Bluebook))
{
conn.Open();
string sql = #"update dbo.Companies
set CompanyName=#CompanyName, AccountNo=#AccountNo
where AccountNo=#OriginalAccountNo;
IF ##ROWCOUNT = 0 RAISERROR('Account number %s not found',16,1,#OriginalAccountNo)";
using (SqlCommand command = new SqlCommand(sql, conn))
{
command.Parameters.Add(new SqlParameter("#CompanyName",SqlDbType.VarChar,100).Value = TextBox_CompanyName.Text;
command.Parameters.Add(new SqlParameter("#AccountNo", SqlDbType.Char, 10).Value = TextBox_Account.Text;
command.Parameters.Add(new SqlParameter("#OriginalAccountNo", SqlDbType.Char, 10).Value = _accountNo;
command.ExecuteNonQuery();
}
}
}
If the row is still not updated as expected, make sure _accountNo contains the proper value.
EDIT:
I added a RAISERROR statement to the SQL batch to facilitate this, which you could leave in the code if the not found condition should never occur.
If the SQL Params are not working, then try this way:
comm = new SqlCommand("update student_detail set s_name= '" + txtname.Text + "', age= "+txtage.Text+" , course=' " + txtcourse.Text + "' where roll_no = " + txtrn.Text + " ", conn);
Try to place the debugger and provide the exact error of the compiler
I have a code for fetching customer_id and I use a SqlDataReader for reading customer_id from SQL Server. I test witch using breakpoint and step by step debugging and I understand the SqlDataReader condition was not compile and compiler jump straight in to the connection.close line:
string strQuery = "select customer_id from Registration where username=#username and password=#password";
SqlConnection connection1 = DBConnection.getConnection();
connection1.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = connection1;
cmd.CommandText = strQuery;
cmd.Parameters.AddWithValue("username", txt1_username.Text);
cmd.Parameters.AddWithValue("password", txt2_password.Text);
string customer_id = cmd.ExecuteScalar() as string;
connection1.Close();
if (customer_id == null)
{
Messages myMsg = new Messages();
myMsg.CreateMessageAlert("The User does not Registered or your using incorect username or password");
}
else {
Session["customer_id"] = customer_id;
}
Although the issue is not very clear, you can try to revise the code taking following into account:
There is no need to open/close db connection for every sql query in a method. Open it once, execute all queries, close. That will make code clear and faster.
As you take connection from somewhere else, make sure it is closed before you open it (Example: Check if SQL Connection is Open or Closed)
You run 2 queries and in both cases you get only 1 result (select count(*), select customer_id). Why then in first case you do ExecuteScalar() and ExecuteReader() in the other?
The other thought is there is no need to have 2 SqlCommand(), etc if you need to return results of 2 queries. Read about Retrieving Multiple Result Sets using NextResult
And last but not least - it seems you need to check if user is already registered and if true, get his id. Why not do it in one shot? The second query is good for both cases - if user does not exist, query will not return any result, if he does - his id will be returned. Doing this way, you would need only one query and less coding.
UPDATE:
The updated code looks more clear and straightforward, but you didn't get the point of my last comment. If you select count(customer_id) you get a count that you don't need. Why not simply select customer_id and check if it was returned or not?
Example:
//string strQuery = "select count(customer_id) from Registration where username=#username and password=#password";
string strQuery = "select customer_id from Registration where username=#username and password=#password";
SqlConnection connection1 = DBConnection.getConnection();
connection1.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = connection1;
cmd.CommandText = strQuery;
cmd.Parameters.AddWithValue("username", txt1_username.Text);
cmd.Parameters.AddWithValue("password", txt2_password.Text);
//int intRowCount = (int)cmd.ExecuteScalar();
string customer_id = cmd.ExecuteScalar() as string;
//txt1_username.Text = intRowCount.ToString(); <-- What's this?
connection1.Close();
//if (intRowCount == 1)
if (customer_id == null)
{
// user does not exist, because sql returned no rows
... <-- do something here
} else {
Session["customer_id"] = customer_id;
}
UPDATE #2:
To troubleshoot
Make sure txt1_username.Text and txt2_password.Text have expected values. It could be that you reset the Text somewhere and that could be the reason why the query returned no result. Try to hardcode the value in the code, for example,
cmd2.Parameters.AddWithValue("username", "admin");
cmd2.Parameters.AddWithValue("password", "123");
Copy-paste entire sql in Sql Server Management Studio (or other tool) and run it from here to ensure what result it returned.
Make sure you execute it against correct database (maybe you have different databases with same tables where data is different).
This is because your username is no longer the username. It is actually 1 because of the line
int intRowCount = (int) cmd.ExecuteScalar();
txt1_username.Text = intRowCount.ToString(); <-- RED FLAG
So in the inside the If, you are actually running
SELECT customer_id FROM registration WHERE username=1 and password=my_password
Comment line 15 and you should do fine.
updated
string strQuery = "select count(*) from Employee where FullName=#username";
SqlConnection connection = DBConnection.getConnection();
connection.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = connection;
cmd.CommandText = strQuery;
cmd.Parameters.AddWithValue("username", txt1_username.Text);
cmd.Parameters.AddWithValue("password", txt2_password.Text);
int intRowCount = (int)cmd.ExecuteScalar();
txt1_username.Text = intRowCount.ToString();
if (intRowCount == 1)
{
string strquery = "select customer_id from Registration where username=#username and password=#password";
SqlCommand cmd2 = new SqlCommand();
cmd2.Connection = connection;
cmd2.CommandText = strquery;
cmd2.Parameters.AddWithValue("username", txt1_username.Text);
cmd2.Parameters.AddWithValue("password", txt2_password.Text);
SqlDataReader reader = cmd2.ExecuteReader();
if (reader.Read())
{
string customerID = reader[0].ToString();
}
}
connection.Close();`
This is complete solution for your issue.
Do not need to open connection everytime. just make sure, connection is being closed once it's used.
con.Open();
cmd2 = new SqlCommand("insert into dailyWorkout('"+RadioButton1.Text+"', '"+RadioButton2.Text+"', '"+RadioButton3.Text+"', '"+RadioButton4.Text+"', '"+RadioButton5.Text+"', '"+Label1.Text+"')", con);
cmd2.ExecuteNonQuery();
Hey guys, been working on this website for a while, but I get an error when putting data into the database saying
Incorrect syntax near ')'.
With other stuff that I'm putting same way it works and this does not.
You should really really REALLY use parametrized queries to avoid SQL injection (and to boost performance; and avoid issues with type conversions etc.)
So I would recommend using code something like this:
// define your *parametrized* SQL statement
string insertStmt = "INSERT INTO dbo.YourTable(Col1, Col2, Col3) VALUES(#Val1, #Val2, #Val3);";
// put SqlConnection and SqlCommand into "using" blocks to ensure proper disposal
using(SqlConnection conn = new SqlConnection("-your-connection-string-here-"))
using(SqlCommand cmd = new SqlCommand(insertStmt, conn))
{
// set the parameters to the values you need
cmd.Parameters.AddWithValue("#Val1", "Some String here");
cmd.Parameters.AddWithValue("#Val2", 42);
cmd.Parameters.AddWithValue("#Val3", DateTime.Today.AddDays(-7));
// open connection, execute query, close connection right away
conn.Open();
int rowsAffected = cmd.ExecuteNonQuery();
conn.Close();
}
Points to remember:
ALWAYS use parametrized queries - do NOT concatenate together your SQL statements!
put the SqlConnection and SqlCommand into using(...) { ... } blocks to ensure proper disposal
always explicitly define the list of columns you want to use in a SELECT and also an INSERT statement
open connection as late as possible, execute query, close connection again right away
That will do the job but I strongly advice using Parameters.
con.Open();
cmd2 = new SqlCommand("insert into dailyWorkout values ('"+RadioButton1.Text+"', '"+RadioButton2.Text+"', '"+RadioButton3.Text+"', '"+RadioButton4.Text+"', '"+RadioButton5.Text+"', '"+Label1.Text+"')", con);
cmd2.ExecuteNonQuery();
Instead of the code above you'd better to use
cmd2 = new SqlCommand("insert into dailyWorkout values (#val1, #val2, #val3,#val4,#val5,#val6)", con);
cmd2.Parameters.AddWithValue("#val1",RadioButton1.Text);
cmd2.Parameters.AddWithValue("#val2",RadioButton2.Text);
cmd2.Parameters.AddWithValue("#val3",RadioButton3.Text);
cmd2.Parameters.AddWithValue("#val4",RadioButton4.Text);
cmd2.Parameters.AddWithValue("#val5",RadioButton5.Text);
cmd2.Parameters.AddWithValue("#val6",Label1.Text)
cmd2.ExecuteNonQuery();
Ok its already been mentioned, don't inject parameters like that.
But if you must, the problem is that your final sql string looks like:
insert into dailyWorkout('string1', 'string2', 'string3', 'string4', 'string5', 'string6')
when it should be
insert into dailyWorkout(columnName1,columnName2,columnName3,columnName4,columnName5,columnName6)
values('string1', 'string2', 'string3', 'string4', 'string5', 'string6')
But you should really consider:
var sqlCmd = new SqlCommand("insert into dailyWorkout(columnName1,columnName2,columnName3,columnName4,columnName5,columnName6) values(#v1, #v2, #v3, #v4, #v5, #v6)", default(SqlConnection));
sqlCmd.Parameters.Add("#v1", SqlDbType.NVarChar).Value = RadioButton1.Text;
sqlCmd.Parameters.Add("#v2", SqlDbType.NVarChar).Value = RadioButton2.Text;
sqlCmd.Parameters.Add("#v3", SqlDbType.NVarChar).Value = RadioButton3.Text;
sqlCmd.Parameters.Add("#v4", SqlDbType.NVarChar).Value = RadioButton4.Text;
sqlCmd.Parameters.Add("#v5", SqlDbType.NVarChar).Value = RadioButton5.Text;
sqlCmd.Parameters.Add("#v6", SqlDbType.NVarChar).Value = Label1.Text;
sqlCmd.ExecuteNonQuery();
How to Run two Update Sql Queries using this Sql Snippet ?
The code mentioned below is updating values only in one table .... i want to update data in two different tables using the code mentioned below :
can anybody reedit this code ?
Try
Using conn = New SqlConnection(constr)
Using cmd = conn.CreateCommand()
conn.Open()
Dim sql As String =
"UPDATE a1_ticket
SET Ticket_no =#ticketNo,
BANK = #bank,
PAID = #paid,
BID = #bid
WHERE ITC = #ticketNo"
cmd.CommandText = sql
cmd.Parameters.AddWithValue("#bank", Literal20.Text)
cmd.Parameters.AddWithValue("#paid", Label1.Text)
cmd.Parameters.AddWithValue("#bid", Literal21.Text)
cmd.Parameters.AddWithValue("#ticketNo", Literal3.Text)
cmd.ExecuteNonQuery()
End Using
End Using
Catch ex As Exception
Response.Write(ex.Message)
End Try
Create a Stored Procedure that updates the two tables and execute it using a StoredProcedure Command...
command.CommandType = CommandType.StoredProcedure;
command.CommandText = "UpdateTheTwoTables";
....
Modify the SQL statement to update the two tables.
Using a Stored Procedure is the cleanest way code wise. If you don't feel comfortable doing it like that, I'm sure you can do it like this:
Try
Using conn = New SqlConnection(constr)
Using cmd = conn.CreateCommand()
conn.Open()
Dim sql As String = "UPDATE a1_ticket SET Ticket_no =#ticketNo, BANK = #bank, PAID = #paid, BID = #bid WHERE ITC = #ticketNo"
cmd.CommandText = sql
cmd.Parameters.AddWithValue("#bank", Literal20.Text)
cmd.Parameters.AddWithValue("#paid", Label1.Text)
cmd.Parameters.AddWithValue("#bid", Literal21.Text)
cmd.Parameters.AddWithValue("#ticketNo", Literal3.Text)
cmd.ExecuteNonQuery()
End Using
//
Using cmd = conn.CreateCommand()
conn.Open()
Dim sql As String = "UPDATE a2_ticket SET Ticket_no =#ticketNo, BANK = #bank, PAID = #paid, BID = #bid WHERE ITC = #ticketNo"
cmd.CommandText = sql
cmd.Parameters.AddWithValue("#bank", Literal20.Text)
cmd.Parameters.AddWithValue("#paid", Label1.Text)
cmd.Parameters.AddWithValue("#bid", Literal21.Text)
cmd.Parameters.AddWithValue("#ticketNo", Literal3.Text)
cmd.ExecuteNonQuery()
End Using
End Using
Catch ex As Exception
Response.Write(ex.Message)
End Try
It's a sketch of what I'm trying to say, you may want to change a few things here and there, but the point is you can just update your two tables one after the other. It's not possible in one update statement afaik.
you can also use
Dim sql As String = # "Query for first update;
Query for second update;";
Well as you havent said anything about the second table, or the data you're sending it. I havent put this through the compiler to verify it, but the concept I'd suggest would be
You could do:
void UpdateDB(String sql, String[][] params)
{
Try
{
SqlConnection conn = New SqlConnection(constr);
SqlCommand cmd = conn.CreateCommand();
conn.Open();
cmd.CommandText = sql;
for(int i=0; i<params.length; i++)
{
cmd.Parameters.AddWithValue(params[i,0] params[i,1]);
}
cmd.ExecuteNonQuery();
}
Catch (Exception ex)
{
Response.Write(ex.Message);
}
}
eg send the SQL and the parameters to the function and have it do all the work..
I have problem while connecting to mysql database using "ADO.NET Driver for MySQL (Connector/NET)"
I got this exception The given key was not present in the dictionary.
Edit:
MySqlConnection con = new MySqlConnection("Server=localhost;Database=pgs_db;Uid=root;Pwd=;");
MySqlCommand com = new MySqlCommand();
com.CommandType = CommandType.StoredProcedure;
com.Connection = con;
com.CommandText = "getStudent";
con.Open();
MySqlDataReader dr =com.ExecuteReader();
GridView1.DataSource = dr;
GridView1.DataBind();
con.Close();
sorry i was using a worng connectionstring
this is a right one :
"server=localhost; user id=user; password=password; database=mydatabase; pooling=false;"
thnx Oded
Without seeing the code, I am guessing you are trying to access a configuration key that does not exist in your application config file.
Edit:
After seeing the code sample, the problem is probably not with connecting to the DB.
I would say that in your GridView, you are binding to a field that is not returned by the DB query.