The code compiles fine without error or warning, but the database does not change. I mean the changes are not saved to the database.
I wrote the following methods:
private void Test2()
{
connection = new SqlConnection();
string Conn = #"Data Source=(LocalDB)\MSSQLLocalDB;"
+ #"AttachDbFilename=|DataDirectory|\User.mdf;"
+ "Integrated Security=True;"
+ "Connect Timeout=30";
// string sqlString = Properties.Settings.Default.ConnectionString;
SqlConnection sqlConnection = new SqlConnection(Conn);
try
{
string SQL = "UPDATE Primuser SET Following = #Following WHERE Insta = #Insta";
SqlCommand sqlCommand = new SqlCommand(SQL, sqlConnection);
sqlCommand.Parameters.AddWithValue("#Following", "123");
sqlCommand.Parameters.AddWithValue("#Insta", "hgd");
sqlCommand.CommandText = SQL;
sqlConnection.Open();
sqlCommand.ExecuteNonQuery();
sqlConnection.Close();
MessageBox.Show("Record Updated");
}
catch (Exception err)
{
MessageBox.Show(err.Message);
}
}
and in this Code, the result is bigger than 0.
private void Test2()
{
connection = new SqlConnection();
connection.ConnectionString = #"Data Source=(LocalDB)\MSSQLLocalDB;"
+ #"AttachDbFilename=|DataDirectory|\User.mdf;"
+ "Integrated Security=True;"
+ "Connect Timeout=30";
SqlCommand command = new SqlCommand();
command.CommandText = "SELECT * FROM Primuser";
command.Connection = connection;
SqlDataAdapter adapter = new SqlDataAdapter();
adapter.SelectCommand = command;
DataSet dataset = new DataSet();
adapter.Fill(dataset, "Primuser");
foreach (DataRow row in dataset.Tables["Primuser"].Rows)
{
if (row["Insta"].ToString() == "1495")
{
row["Following"] = "1024";
}
}
SqlCommandBuilder builder = new SqlCommandBuilder(adapter);
try
{
var result = adapter.Update(dataset, "Primuser");
if (result > 0)
MessageBox.Show("Update Successful.");
else
MessageBox.Show("Update Failed.");
}
catch (SqlException ex)
{
MessageBox.Show(ex.Message);
}
}
but the database does not get changed. There are no errors and other query is working. I can insert, delete or select, but update is not working.
Related
I want to insert document number into adjustments_config table in the vm server like this:
public string conString = "Data Source=vmrserver;Initial Catalog=Commission_web;Integrated Security=True";
SqlConnection con = new SqlConnection(conString);
con.Open();
if(con.State == System.Data.ConnectionState.Open)
{
string q = "insert into adjustments_config(document_number)values('" + TextBoxDocNo.Text + "')";
SqlCommand cmd = new SqlCommand(q, con);
cmd.ExecuteNonQuery();
Response.Redirect("About.aspx");
}
I can't possibly tell what you problem is without more information but your SQL is vulnerable to SQL injection. Perhaps the problem with your code is that your document number has an apostrophe in it, causing your vulnerable code to blow up.
Try this to get you started:
try
{
using(var con = new SqlConnection(conString))
using(var cmd = new SqlCommand("insert into adjustments_config(document_number)values(#docNumber)", con)
{
con.Open();
cmd.Parameters.AddWithValue("#docNumber", TextBoxDocNo.Text);
var rowsAffected = cmd.ExecuteNonQuery();
// ..validate rows affected
Response.Redirect("About.aspx");
}
}
catch(SqlException ex)
{
MessageBox.Show(ex.Message);
}
I have added a new value into my combobox and it should be displayed based on what I have in my database. But unfortunately, the new value does not display out. Below are my codes.
string dbConn = "Data Source=.\\SQLEXPRESS;AttachDbFilename=C:\\Users\\SONY\\Desktop\\FinalYearProject\\FinalYearProject\\bin\\Debug\\housewife.mdf;Integrated Security=True;User Instance=True";
void fill_Combo() {
SqlConnection conn = new SqlConnection(dbConn);
try {
conn.Open();
string query = "Select * From Food";
SqlCommand cmd = new SqlCommand(query, conn);
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read()) {
string name = dr.GetString(1);
comboBox1.Items.Add(name);
}
conn.Close();
}
catch(Exception ex){
MessageBox.Show(ex.Message);
}
}
You should be using an observable collection as the data source and binding to that collection. See Add items to comboBox in WPF
Hi please try something like this, hope it helps
string dbConn = "Data Source=.\\SQLEXPRESS;AttachDbFilename=C:\\Users\\SONY\\Desktop\\FinalYearProject\\FinalYear Project\\bin\\Debug\\housewife.mdf;Integrated Security=True;User Instance=True";
void fill_Combo() {
SqlConnection conn = new SqlConnection(dbConn);
try {
conn.Open();
string query = "Select * From Food";
SqlCommand cmd = new SqlCommand(query, conn);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds)
combobox1.DataSourse = ds;
combobox1.DisplayMember = "fieldname";
combobox1.ValueMember = "fieldname";
}
catch(Exception ex){
MessageBox.Show(ex.Message);
}
}
I have a data base in SQL Server 2008 and connecting it in WPF application.I want to read data from table and show in datagrid. Connection is successfully created but when I show it in grid,it show db error(Exception handling).
This is what I am doing.Thanks in advance.
try
{
SqlConnection thisConnection = new SqlConnection(#"Server=(local);Database=Sample_db;Trusted_Connection=Yes;");
thisConnection.Open();
string Get_Data = "SELECT * FROM emp";
SqlCommand cmd = new SqlCommand(Get_Data);
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataTable dt = new DataTable("emp");
sda.Fill(dt);
MessageBox.Show("connected");
//dataGrid1.ItemsSource = dt.DefaultView;
}
catch
{
MessageBox.Show("db error");
}
It shows connected when i comment the line sda.Fill(dt);
Your SqlCommand doesn't know you opened the connection- it requires an instance of SqlConnection.
try
{
SqlConnection thisConnection = new SqlConnection(#"Server=(local);Database=Sample_db;Trusted_Connection=Yes;");
thisConnection.Open();
string Get_Data = "SELECT * FROM emp";
SqlCommand cmd = thisConnection.CreateCommand();
cmd.CommandText = Get_Data;
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataTable dt = new DataTable("emp");
sda.Fill(dt);
dataGrid1.ItemsSource = dt.DefaultView;
}
catch
{
MessageBox.Show("db error");
}
You don't assign the command any connection. You open the connection then create a command, but don't link the two.
Try something like:
SqlConnection conn = new SqlConnection(#"Server(local);Database=Sample_db;Trusted_Connection=Yes;");
conn.Open();
string sql= "SELECT * FROM emp";
SqlCommand cmd = new SqlCommand(sql);
cmd.Connection = conn;
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataTable dt = new DataTable("emp");
sda.Fill(dt);
Assign Connection Object to SqlCommand Object.
using (SqlConnection connection = new SqlConnection(
connectionString))
{
SqlCommand command = new SqlCommand();
command.Connection = connection;
command.CommandTimeout = 15;
command.CommandType = CommandType.Text;
command.CommandText = queryString;
connection.Open();
//Perfom desired Action
}
Add thisConnection as 2nd parameter in
Sqlcommand cmd = new SqlCommand(Get_Data, thisConnection)
try {
string connectionstring = "#"
Server = (local) Database = Sample_dbTrusted_Connection = Yes;
"";
SqlConnection thisConnection = new SqlConnection(connectionstring);
thisConnection.Open();
string Get_Data = "SELECT * FROM emp";
SqlCommand cmd = new SqlCommand(Get_Data, thisConnection);
SqlDataAdapter sda = new SqlDataAdapter(cmd);`
DataTable dt = new DataTable("emp");
sda.Fill(dt);
MessageBox.Show("connected");
//dataGrid1.ItemsSource = dt.DefaultView;
} catch {
MessageBox.Show("db error");
}
I use this code with Oracle and hope it will help you.
First add reference Oracle.DataAccess then add namespace using Oracle.DataAccess.Client;
And using the following code
try
{
string MyConString = "Data Source=localhost;User Id= yourusername;Password=yourpassword;";
using (OracleConnection connection = new OracleConnection(MyConString))
{
connection.Open();
sqldb1 = "select * from DEMO_CUSTOMERS;";
using (OracleCommand cmdSe1 = new OracleCommand(sqldb1, connection))
{
DataTable dt = new DataTable();
OracleDataAdapter da = new OracleDataAdapter(cmdSe1);
da.Fill(dt);
db1.ItemsSource = dt.DefaultView;
}
connection.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
XAML code:
<DockPanel>
<DataGrid Margin="10.0" DockPanel.Dock="Left" Name="db1" AutoGenerateColumns="True" >
</DataGrid>
</DockPanel>
public DataTable Execute(string cmd)
{
bool networkUp = System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable();
if (networkUp)
{
try
{
SqlConnection connection = new SqlConnection("ConnectionString");
SqlCommand command = new SqlCommand(cmd);
using (SqlDataAdapter sda = new SqlDataAdapter())
{
DataTable dt = new DataTable();
sda.SelectCommand = command;
command.Connection = connection;
connection.Open();
sda.Fill(dt);
connection.Close();
if (dt != null && dt.Columns.Count > 0)
return dt;
else
return null;
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
return null;
}
}
else
{
Console.WriteLine("Network is disconnect");
return null;
}
return null;
}
or :
public void ExecuteNonQuery(string cmd)
{
bool networkUp = System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable();
if (networkUp)
{
try
{
SqlConnection connection = new SqlConnection("ConnectionString");
SqlCommand command = new SqlCommand(cmd);
command.Connection = connection;
connection.Open();
command.ExecuteNonQuery();
connection.Close();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}
When debugger is applied the query-line shows no data in textBox1.Text.my code is following:
namespace SeparateConnection
{
class clsGridView
{
Connection co2 = new Connection();
//display our global varaible for connection
SqlConnection myconn3 = new SqlConnection("data source=M-SULEMAN-PC;initial catalog=dbmsLogin;integrated security=sspi");
public void Delete()
{
co2.setconn();
try
{
DialogResult result = MessageBox.Show("Are you sure you want to delete ?", "Message",
MessageBoxButtons.YesNo, MessageBoxIcon.Question);
if (result == DialogResult.Yes)
{
//myconn3.Open();
DataTable table2 = new DataTable();
frmGridView gd = new frmGridView();
SqlDataAdapter myadd2 = new SqlDataAdapter("Delete from tblLogin where UserName ='" + gd.textBox1.Text + "'", myconn3);
myadd2.Fill(table2);
//Sqlcommandbulider to allow changes to database
SqlCommandBuilder mybuild = new SqlCommandBuilder(myadd2);
//Update the database
myadd2.Update(table2);
//Close the connection
myconn3.Close();
}
else
return;
}
catch (Exception error)
{
MessageBox.Show(error.ToString());
}
}
----------when I use the same class for calling and defining the method..there is no problem
To delete data you must follow this pattern:
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "Delete from tblLogin where UserName = #param";
cmd.Parameters.Add("#param", gd.textBox1.Text);
cmd.Connection = conn;
cmd.ExecuteNonQuery();
why dont you try out something like this
string connetionString = null;
SqlConnection connection ;
SqlDataAdapter adapter = new SqlDataAdapter();
string sql = null;
connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password";
connection = new SqlConnection(connetionString);
sql = "delete product where Product_name ='Product6'";
try
{
connection.Open();
adapter.DeleteCommand = connection.CreateCommand();
adapter.DeleteCommand.CommandText = sql;
adapter.DeleteCommand.ExecuteNonQuery();
MessageBox.Show ("Row(s) deleted !! ");
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
I am new to C#.
Kindly tell me what`s wrong with this code. I am inserting data in data base using two input fields EndValueTextBox and StartValueTextBox .
I am receiving following error. "Object reference not set to an instance of an object"
private void buttonSave_Click(object sender, EventArgs e)
{
connection = new System.Data.SqlClient.SqlConnection();
da = new SqlDataAdapter();
try
{
connection.ConnectionString = "Data Source=.\\SQLEXPRESS;AttachDbFilename='G:\\C#.Net\\Forms Practice\\WindowsFormsPractice1\\WindowsFormsPractice1\\WindowsFormsPractice1.mdf';Integrated Security=True;Connect Timeout=30;User Instance=True";
}
catch (System.Exception ex)
{
MessageBox.Show(ex.Message,"Connection String");
}
try
{
connection.Open();
string sql = "insert into TBLWORKERS (first_name , last_name )" + " values('" + StartValueTextBox.Text + "', '" + EndValueTextBox.Text + ")";
//SqlDataAdapter da = new SqlDataAdapter(query, connString);
da.InsertCommand.CommandText = sql;
da.InsertCommand.ExecuteNonQuery();
}
catch (System.Exception ex)
{
MessageBox.Show(ex.Message, "Connection open");
}
}
Your SqlDataAdapter is never assigned a connection to execute the query on. You need to associate the SqlConnection with the SqlDataAdapter during or after construction.
This line da.InsertCommand.CommandText = sql; has to be in that way:
da.InsertCommand = new SqlCommand(sql);
At what point you are the exception? Probably those line
System.Data.SqlClient.SqlConnection connection = new System.Data.SqlClient.SqlConnection();
SqlDataAdapter da = new SqlDataAdapter();
string connetionString = "Data Source=.\\SQLEXPRESS;AttachDbFilename='G:\\C#.Net\\Forms Practice\\WindowsFormsPractice1\\WindowsFormsPractice1\\WindowsFormsPractice1.mdf';Integrated Security=True;Connect Timeout=30;User Instance=True";
SqlDataAdapter adapter = new SqlDataAdapter();
string sql = "insert into TBLWORKERS (first_name , last_name )" + " values('" + StartValueTextBox.Text + "', '" + EndValueTextBox.Text + ")";
SqlConnection connection = new SqlConnection(connetionString);
try {
connection.Open();
adapter.InsertCommand = new SqlCommand(sql, connection);
adapter.InsertCommand.ExecuteNonQuery();
} catch (Exception ex) {
MessageBox.Show(ex.Message);
}
Here's a minor rewrite of your code (not tested) that should take care of the SqlDataAdapter not having the connection object assigned and also demonstrates how to use parameterized queries to help defend against SQL Injection attacks:
private void buttonSave_Click(object sender, EventArgs e)
{
try
{
// The using block will automatically dispose of your connection when
// the block is exited and is considered standard practice.
using (SqlConnection connection = new SqlConnection("Data Source=.\\SQLEXPRESS;AttachDbFilename='G:\\C#.Net\\Forms Practice\\WindowsFormsPractice1\\WindowsFormsPractice1\\WindowsFormsPractice1.mdf';Integrated Security=True;Connect Timeout=30;User Instance=True";))
{
SqlDataAdpter da = new SqlDataAdapter();
connection.Open();
// Assign the SqlConnection object to the SqlDataAdapter
da.Connection = connection;
// Parameterize the query as shown below
string sql = "INSERT INTO TBLWORKERS(first_name, last_name) VALUES(#first_name, #last_name)";
da.InsertCommand.CommandText = sql;
// Add the values for the parameters
da.InsertCommand.Parameters.Add("#first_name", SqlDbType.NVarChar, 25, StartValueTextBox.Text);
da.InsertCommand.Parameters.Add("#last_name", SqlDbType.NVarChar, 25, EndValueTextBox.Text);
// Execute the query - rows will have the number of rows
// affected. should be 1 in this case if succesful
int rows = da.InsertCommand.ExecuteNonQuery();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Connection open");
}
}