SQL Update Query Not updating Simple Record - c#

Hi I am using simple update query to update the password of a Admin login table it is not giving me any kind of error but it is not updating my record also.
please tell me what can be the problem
I am using Visual Studio 2012 | SQL SERVER 2008.
here is the Code.
protected void ButtonSubmit_Click(object sender, EventArgs e)
{
obj.OpenConection();
obj.ExecuteQueries("Update Admin_Login set Username='" + TextUsername.Text + "',Password='" + TextPassword.Text + "' where Username='" + TextUsername.Text + "'");
obj.CloseConnection();
}
=> ExecuteQueries() here is a function to execute different queries working fine every where even on other update queries but not here.

Related

C# Logging in system only works with first value of database

I'm a beginner to C# so help would be much appreciated. I'm attempting to code a logging in system but I can only successfully log in with the first line of data (username=admin , password=admin). I can't seem to log in from other data in the database (username=bryan , password=123). This is the code.
searchOLEDB.CommandText = "SELECT * FROM LOGIN where Username='" + LoginIDTextBox.Text + "' AND Password='" + LoginPasswordTextBox.Text + "'";
searchOLEDB.Connection = cnnOLEDB;
OleDbDataReader dr = searchOLEDB.ExecuteReader();
if (dr.Read())
{
MessageBox.Show("Logged In");
}
else
{
MessageBox.Show("Invalid Password");
}
dr.Close();
First, you should never concatenate sql query like you did. This will allow SQL Injection. You should use parameters.
See this post for examples :
using parameters inserting data into access database
P.S. I would also recommend to not store password in clear into your database.

How to format datatimer to insert in a DB

Could someone help me with an Insert ? I'm trying to give insert in the DB but I have to convert the dateTimePicker pro to the right format, I do not know if it is exactly like this, I already tried google and tested it in several ways and none worked for me.
The first image is the INSERT, which is in a class.
The second image is the own button to insert.
The third image is the Database (yes I did in phpmyadmin of wamp msm pq is a very small and simple DB).
The error that happens when I try to insert is simply in that throw; Of the insert, and I think it's the question of help. Thank you to anyone who can help.
i just cant format the "Datav".
public void inserir_produtov()
{
try
{
string inserir1 = "INSERT INTO venda VALUES (null, '" + Datav.ToString("yyyy-MM-dd HH:mm:ss") + "', '" +
Id + "','" +
Quantidadev + "','" +
Valorv.ToString().Replace(',', '.') + "');";
bancodedados1.ExecutarComandos(inserir1);
}
catch
{
throw;
}
}
Here is the Button to insert:
private void btngravar1_Click(object sender, EventArgs e)
{
vendas.Id = int.Parse(txtidproduto.Text);
vendas.Quantidadev = int.Parse(txtquantidade2.Text);
vendas.Valorv = double.Parse(txtvalor.Text);
vendas.Datav = DateTime.Parse(dateTimePicker1.Text);
if (txtidvenda.Text == "")
{
vendas.inserir_produtov();
Limpar();
MessageBox.Show("Dados inseridos com sucesso.");
}
Use parameters instead so you don't need to format. This will also help prevent SQL injection too.
Have a look at this link:
SQL Insert Query Using C#

DNN Module compiler error: CS

I am using Module Creator templates for Dotnetnuke 7 trying to make our staff sign in-out module function. Am working with code developed by a volunteer intern from France years ago for DNN 5 Beta. (Some of the spelling is French) I am not a coder myself so am struggling to make the code work in DNN 7. I've managed to figure out a lot of the compiling errors by reading this web site. Thank you. This one has me absolutely stumped:
Error: France is currently unavailable.
DotNetNuke.Services.Exceptions.ModuleLoadException:
d:\HostingSpaces\tgpintra\tgpintranet.org\wwwroot\DesktopModules\TGP\France\View.ascx.cs(176): error CS1010: Newline in constant --->
The source code starting at line 175 is below:
//Set the parameters for updating user's information
SqlUpdate.UpdateCommand = "UPDATE Scotland SET
statut=#statut, timereturn=#timereturn, date=#date, comment=#comment
WHERE name='" +
DotNetNuke.Entities.Users.UserController.GetCurrentUserInfo().Username +
"'";
SqlUpdate.UpdateParameters.Add("statut",
DropDownList2.SelectedValue);
SqlUpdate.UpdateParameters.Add("timereturn",
timereturn.Text);
SqlUpdate.UpdateParameters.Add("date", DateTime.Now.AddHours
(-2).ToString());
SqlUpdate.UpdateParameters.Add("comment", comment.Text);
SqlUpdate.Update();
//Insert a log for the user and his/her new status
SqlConnection MaSqlCnx = new SqlConnection();
MaSqlCnx.ConnectionString = "Server=someserver.
net;Initial Catalog=tgpintra_db;User
Id=theusername;Password=thepassword;";
MaSqlCnx.Open();
SqlCommand MaSqlCmd = new SqlCommand();
MaSqlCmd.Connection = MaSqlCnx;
MaSqlCmd.CommandText = "Insert into ScotlandSchedule(name,
status, time) Values('" +
DotNetNuke.Entities.Users.UserController.GetCurrentUserInfo().FullName +
"', '" + DropDownList2.SelectedValue + "', '" + DateTime.Now.AddHours(-
2).ToString() + "');";
MaSqlCmd.ExecuteNonQuery();
MaSqlCnx.Close();
//Reload the page to update data
Response.AppendHeader("Refresh", "1");
}
Remove the line breaks in the assignment to SqlUpdate.UpdateCommand. You can only have it on one line.
There are two places that will cause this error:
SqlUpdate.UpdateCommand = "UPDATE ...
and
MaSqlCnx.ConnectionString = "Server=mssql02 ...
The strings in the lines above each need to be on a single line, or have a # character before the opening " character.

connect mysql database in websever with c# application

i have a PHP website and MySQL database in same web sever. i wont to connect that MySQL database with c# application. my c# application in run another computer.
how can i connect that MySQL database ?
First make sure you have downloaded and installed the MySQL Connector/NET from the MySQL official website. In this article, I will use the Connector/NET version 6.1.
Then add MySql.Data namespace in Reference
Then you can use mysql in .net
now create a connection strin like this
class ConnectToMySql{
private MySqlConnection connection;
private void Initialize()
{
server = "localhost";
database = "connectcsharptomysql";
uid = "username";
password = "password";
string connectionString;
connectionString = "SERVER=" + server + ";" + "DATABASE=" +
database + ";" + "UID=" + uid + ";" + "PASSWORD=" + password + ";";
connection = new MySqlConnection(connectionString);
connection.Open();
}
}
Then
1 Create a MySQL command.
2 Assign a connection and a query to the command. This can be done using the constructor
3 using the Connection and the CommandText methods in the MySqlCommand class.
4 Create a MySqlDataReader object to read the selected records/data.
5 Execute the command.
6 Read the records and display them or store them in a list.
7 Close the data reader.
8 Close the connection.
I tooth this will help full for you . now you can start working on mysql in .NET
Best of luck
you firstly have to add mysql ref to your project:
plz right click on your project and go to the ref part in it
after that try to find mysl.conncetor and tick it
and refresh your project and firstly try to add using mysql.net.client
now you can use data base located in the mysql db from c# coding
be sure you have downloaded both mysql connector and installaton which is about 500 mb files.
class ConnectToMySql{
private MySqlConnection mscon;
private void Initialize()
{
server = "localhost";
database = "your own database name";
uid = " your username";
password = "your password";
string const;
connectionString = "SERVER=" + server + ";" + "DATABASE=" +
database + ";" + "UID=" + uid + ";" + "PASSWORD=" + password + ";";
mscon= new MySqlConnection(const);
mscon.Open();
}
}

using Service Based Database in VS2010 Ultimate

I have been working on a project related to database (.mdf). I have created some windows forms in visual studio using C#. Basically these forms work together to store, update and delete data from the Service Based Database i created.
The problem is when i build the project, it builds fine, no errors. It inserts a data provided from textboxes to the datagridview too as intended. But as soon as i stop the current debugging, and then rerun it again, all the data provided previously is lost from the datagridview!!
I cant understand why this is happening. anyone please help me. Im totally new to this stuff.. a bit of guidance would be heartily appreciated.
when i had previously used MySQL for the same purpose, the updated data would be permanently stored to the database, but since i migrated from the MySQL to SQL Server's Service Based Database, i get such confusing error.
......
void loadData()
{
SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["baikalpik_bidhut_sewaConnectionString"].ToString());
SqlCommand cmd = new SqlCommand("SELECT SNo,Customer_ID, Citizenship_No, Name, Subscription_Date, Phone_No, Location,Locality,Bulbs,Deposit,Monthly_Charge FROM customerinformation;", con);
try
{
SqlDataAdapter adp = new SqlDataAdapter();
adp.SelectCommand = cmd;
DataTable dt = new DataTable();
adp.Fill(dt);
dataGridViewCustomerInformation.DataSource = dt;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void buttonAdd_Click(object sender, EventArgs e)
{
try
{
float m_chrg = Convert.ToInt64(textBoxBulbs.Text)*500;
SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["baikalpik_bidhut_sewaConnectionString"].ToString());
SqlCommand cmd = new SqlCommand("INSERT INTO customerinformation(SNo,Customer_ID,Citizenship_No,Name,Subscription_Date,Location,Locality,Bulbs,Deposit,Phone_No,Monthly_Charge) values('" + textBoxSNo.Text + "','" + textBoxCustomerID.Text + "','" + textBoxCitizenshipNumber.Text + "','" + textBoxName.Text + "','" + textBoxSubscriptionDate.Text + "','" + textBoxLocation.Text + "','" + textBoxLocality.Text + "','" + textBoxBulbs.Text + "','" + textBoxDeposit.Text + "','" + textBoxPhoneNumber.Text + "','" + m_chrg + "')", con);
con.Open();
SqlDataReader reader = cmd.ExecuteReader();
dt = new DataTable();
dt.Load(reader);
con.Close();
dataGridViewCustomerInformation.DataSource = dt;
loadData();
MessageBox.Show("Entry Added!");
fillListbox();
textBoxSNo.Clear();
textBoxBulbs.Clear();
textBoxCitizenshipNumber.Clear();
textBoxCustomerID.Clear();
textBoxDeposit.Clear();
textBoxLocality.Clear();
textBoxLocation.Clear();
textBoxPhoneNumber.Clear();
textBoxName.Clear();
textBoxSubscriptionDate.Clear();
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}
If you have your MDF listed in your project files then the property Copy To Output Directory handles how your MDF file is copied to the output directory (BIN\DEBUG or BIN\RELEASE).
If this property is set to Copy Always, then when you run your program a fresh copy of your database file is copied from the project folder to the output effectively destroying every data that you have inserted, modified, deleted in the previous run of your program.
The best solution to this dilemma is to add the MDF file as a permanent database inside your current install of Sql Server and adjust your connection string. And of course set the property to Copy Never
In alternative you could set to Copy if newer. This will allow to change the database schema inside the Server Explorer and let the Visual Studio IDE copy the new structure only after you have made changes.
UPDATE BUT IMPORTANT Not related to your actual question, but your insert query is a serious problem. Do not use string concatenation to build a sql command text. Particularly if the partial text comes from user input. You could face syntax errors (if someone places a single quote inside a text box) or worst, a Sql Injection problem (see here for a funny explanation)
To find good examples of Insert search for 'parametrized query'

Categories