I need help in query builder c#- delete doesn't work - c#

I have a small project in c# and ms-access. I use query builder to manage my tables in ms-access.
The problem is, select query works great, update query works great, but delete doesn't work and there is no error message!
Please help.
public DataSet Update(DataSet ds)
{
using (cn)
{
OleDbDataAdapter adapter = new OleDbDataAdapter();
string queryString = "SELECT [taskId],[resourceId] FROM [mytable]";
cn.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + _conStrName + ";User Id=admin;Password=;";
OleDbConnection connection = new OleDbConnection(cn.ConnectionString);
adapter.SelectCommand = new OleDbCommand(queryString, connection);
adapter.SelectCommand.CommandText = queryString;
OleDbCommandBuilder builder = new OleDbCommandBuilder(adapter);
adapter.Update(ds.Tables["mytable";"]);
return ds;
}
public DataSet Update(DataSet ds)
{
using (cn)
{
OleDbDataAdapter adapter = new OleDbDataAdapter();
string queryString = "SELECT [taskId],[resourceId] FROM [mytable]";
cn.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + _conStrName + ";User Id=admin;Password=;";
OleDbConnection connection = new OleDbConnection(cn.ConnectionString);
adapter.SelectCommand = new OleDbCommand(queryString, connection);
adapter.SelectCommand.CommandText = queryString;
OleDbCommandBuilder builder = new OleDbCommandBuilder(adapter);
adapter.Update(ds.Tables["mytable";"]);
return ds;
}
==================================

If you are using OleDb try something like:
public static int DeleteStudentInfo(long studentNum)
{
var cmd = new OleDbCommand("DELETE FROM Students WHERE studentID = #studentId");
cmd.Parameters.Add("#studentId", OleDbType.BigInt).Value = studentNum;
return CallNonQuery(cmd);
}
private static int CallNonQuery(OleDbCommand query)
{
int rowsAffected;
var conn = new OleDbConnection(ConfigSettingsManager.DBConnectionString);
query.Connection = conn;
try
{
conn.Open();
rowsAffected = query.ExecuteNonQuery();
}
catch (Exception)
{
return -1;
}
finally
{
conn.Close();
}
return rowsAffected;
}
Replacing ConfigSettingsManager.DBConnectionString with your connection string.

Use:
DELETE FROM Store_Information WHERE store_name = "Los Angeles"

Related

SqlDataAdapter is not updating datatable in the database

I'm trying to update datatable in the database using a SqlDataAdapter. I don't see any errors and also it's not updating the database.
I tried other solutions in the stackoverflow but still no luck. Here is my code:
public void Update(DataTable dt, String tableName)
{
try
{
SqlDataAdapter da = new SqlDataAdapter();
using (SqlConnection connection = new SqlConnection(ConnectionString))
{
da.SelectCommand = new SqlCommand("SELECT * FROM " + tableName, connection);
SqlCommandBuilder cmdBuilder = new SqlCommandBuilder(da);
da.UpdateCommand = cmdBuilder.GetUpdateCommand(true);
da.AcceptChangesDuringUpdate = true;
int res = da.Update(dt);
}
}
catch (Exception oEx)
{
System.Diagnostics.Debug.WriteLine("Ex: " + oEx);
}
}
Thanks in advance for your help!

How to Reuse Logic Without Copy/Pasting Blocks of Code - C#

My project reuses the code below multiple times with only a few variables changing. I've noted the values that change with e.g. ***value***.
if (comboBox1.Text == ***"Most recent first"***)
{
string dgvconn = #"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\n0740572\Projects\CW\CW\bin\Debug\Database1.mdf;Integrated Security=True";
string sql = "select * from Records where UserID = #userID Order By ***Date Desc***";
SqlConnection connection = new SqlConnection(dgvconn);
SqlDataAdapter dataadapter = new SqlDataAdapter(sql, connection);
dataadapter.SelectCommand.Parameters.AddWithValue("#userID", currentUserID);
DataSet ds = new DataSet();
connection.Open();
dataadapter.Fill(ds, "Records");
connection.Close();
recordsDataGridView.DataSource = ds;
recordsDataGridView.DataMember = "Records";
}
How can I use this same logic, with different values, without copying and pasting the if statement multiple times?
Sounds to me you want something like:
private void foo(string matchText, string sortBy) {
if (comboBox1.Text == matchText)
{
string dgvconn = #"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\n0740572\Projects\CW\CW\bin\Debug\Database1.mdf;Integrated Security=True";
string sql = "select * from Records where UserID = #userID Order By " + sortBy;
SqlConnection connection = new SqlConnection(dgvconn);
SqlDataAdapter dataadapter = new SqlDataAdapter(sql, connection);
dataadapter.SelectCommand.Parameters.AddWithValue("#userID", currentUserID);
DataSet ds = new DataSet();
connection.Open();
dataadapter.Fill(ds, "Records");
connection.Close();
recordsDataGridView.DataSource = ds;
recordsDataGridView.DataMember = "Records";
}
}//foo
//Call the method
foo("Most recent first", "Date DESC");
foo("Most recent last", "Date");
foo("By Username", "User");

C# & SQL Server : searching all database columns and populating datagrid

I am writing a a C# application, and I am stuck at searching the database and populating a data grid view. However I want to use this with command builder.
The issue is, I need the search to work across all columns in the database. I thought using OR and LIKE statements would do this. But instead I get either invalid syntax or no column name exists in the search.
Does anyone know a solution?
My current .cs:
private void btnSearchJob_Click(object sender, EventArgs e)
{
try
{
SqlConnection con = new SqlConnection();
con.ConnectionString = (#"Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=MTR_Database;Integrated Security=True");
string selectQuery = "SELECT * FROM dbo.[" + cmbJobName.Text + "] WHERE ([Job Name] LIKE " +txtSearchJob.Text+ " OR [Manufacturer] LIKE " +txtSearchJob.Text+ ")";
// DataAdapter
myDA = new SqlDataAdapter(selectQuery, con);
// SqlCommand
SqlCommand myCMD = new SqlCommand(selectQuery, con);
// DataAdapter to Command
myDA.SelectCommand = myCMD;
// Define Datatable
myDT = new DataTable();
// Command Builder (IS GOD!)
SqlCommandBuilder cb = new SqlCommandBuilder(myDA);
// Teach Command builder to be a boss!
myDA.UpdateCommand = cb.GetUpdateCommand();
myDA.InsertCommand = cb.GetInsertCommand();
myDA.DeleteCommand = cb.GetDeleteCommand();
// Fill the DataTable with DataAdapter information
myDA.Fill(myDT);
// Fill DataTable with Database Schema
myDA.FillSchema(myDT, SchemaType.Source);
// Bind The Data Table to the DataGrid
dataGridView1.DataSource = myDT;
// AutoSize Datagrid Rows and Colums to fit the Datagrid
dataGridView1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells;
dataGridView1.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.AllCells;
}
// Catch Exception
catch (Exception ex)
{
MessageBox.Show(this, ex.Message, "SQL ERROR", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
NOTE:
I am aware of using parameters, I am simply using this to see if it will work when I will add parameters later.
this is what I use to get everything back into a DataTable
//'places the call to the system and returns the data as a datatable
public DataTable GetDataAsDatatable(List<SqlParameter> sqlParameters, string connStr, string storedProcName)
{
var dt = new DataTable();
var sqlCmd = new SqlCommand();
using (var sqlconn = new SqlConnection(connStr))
{
sqlCmd.Connection = sqlconn;
sqlCmd.CommandType = CommandType.StoredProcedure;
sqlCmd.CommandText = storedProcName;
sqlCmd.CommandTimeout = 5000;
foreach (var sqlParam in sqlParameters)
{
sqlCmd.Parameters.Add(sqlParam);
}
using (var sqlDa = new SqlDataAdapter(sqlCmd))
{
sqlDa.Fill(dt);
}
}
sqlParameters.Clear();
return dt;
}
//'places the call to the system and returns the data as a datatable
public DataTable GetDataAsDatatable(string connStr, string query)
{
var dt = new DataTable();
var sqlCmd = new SqlCommand();
using (var sqlconn = new SqlConnection(connStr))
{
sqlCmd.Connection = sqlconn;
sqlCmd.CommandType = CommandType.Text;
sqlCmd.CommandText = query;
sqlCmd.CommandTimeout = 5000;
using (var sqlDa = new SqlDataAdapter(sqlCmd))
{
sqlDa.Fill(dt);
}
}
return dt;
}
hopefully this is pretty self explanatory to you, however pass in a list of SQL Parameters, connection string, and the stored procedure name, or use the second one where you pass in the inline SQL and the connection string.
I think you are missing ' in the query. Try this...
string selectQuery = "SELECT * FROM dbo.[" + cmbJobName.Text + "] WHERE ([Job Name] LIKE '" +txtSearchJob.Text+ "' OR [Manufacturer] LIKE '" +txtSearchJob.Text+ "')";

C# connection with MS access is not working?

When I start debugging and I add some clients, I can add them, update them and read them. But the newly added clients won't save in my database. I've checked if I'm using the right file location and I am:
public class DBaccess
{
private static string connectionstr;
static DBaccess()
{
string mdffile;
mdffile = #"C:\Users\rik\Documents\Visual Studio 2010\Projects\Week-2-Opdracht\Database\Clienten.accdb";
connectionstr = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + mdffile + ";";
}
public static DataSet Getwaardenquery(string sqlstr)
{
DataSet ds = new DataSet();
Console.WriteLine(sqlstr);
OleDbConnection con = new OleDbConnection(connectionstr);
OleDbDataAdapter dap = new OleDbDataAdapter(sqlstr, con);
dap.Fill(ds);
return ds;
}
public static int Uitvoerenquery(string sqlstr)
{
int resultaat = -1;
Console.WriteLine(sqlstr);
OleDbConnection con = new OleDbConnection(connectionstr);
OleDbCommand cmd = new OleDbCommand(sqlstr, con);
try
{
con.Open();
resultaat = cmd.ExecuteNonQuery();
}
catch (Exception exp)
{
string x = exp.Message;
}
finally
{
if (con.State == ConnectionState.Open)
{
con.Close();
}
}
return resultaat;
}
}
}
At first check your connection string is correct or not by making a manual connection.
For help follow the given link
http://www.c-sharpcorner.com/UploadFile/b8d90a/connect-oledb-database-in-C-Sharp-in-easy-steps/
your code contain extra semicolon
connectionstr = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source='" + mdffile + "'";
syntax error

Provider & query

I want to create a C # application that can create and populate a DataTable.
Here is my code:
public DataTable GetData(string query)
{
DbProviderFactory factory = DbProviderFactories.GetFactory("System.Data.OracleClient");
using (DbConnection conn = factory.CreateConnection())
{
try
{
DbConnectionStringBuilder csb = factory.CreateConnectionStringBuilder();
csb["Data Source"] = #"";
csb["User Id"] = #"";
csb["Password"] = #"";
conn.ConnectionString = csb.ConnectionString;
conn.Open();
using (DbCommand cmd = conn.CreateCommand())
{
cmd.CommandText = query;
using (DataTable dt = new DataTable())
{
DbDataAdapter da = factory.CreateDataAdapter();
cmd.CommandType = CommandType.Text;
da.SelectCommand = cmd;
da.Fill(dt);
return dt;
}
}
}
catch (Exception ex)
{
throw new Exception("Error", ex);
}
finally
{
if (conn.State != ConnectionState.Closed)
conn.Close();
}
}
}
In a second time, I have a class containing my various queries.
public class Query
{
public string SQL;
public string query1()
{
this.SQL = "select * from table1"
return this.SQL;
}
public string query2(string param)
{
this.SQL = "select * from table1 where id = '" + param + "' ";
return this.SQL;
}
I wish I could go query1 and / or query2 as parameter of my method GetData.
public DataTable GetData(query1)
{
//...
}
But I do not know how!
Thank you in advance for your help!

Categories

Resources