using WHERE in my Insert query statement - c#

string conString = #"Provider=Microsoft.ACE.OLEDB.12.0;
Data Source=C:\Users\user\Documents\Visual Studio 2010\Projects\Timetable\Timetable\bin\Debug\timetabledata.accdb";
//create the database query
string query = "SELECT * FROM relation";
OleDbConnection conn = new OleDbConnection(conString);
conn.Open();
// create the DataSet
DataSet ds = new DataSet();
// create the adapter and fill the DataSet
OleDbDataAdapter adapter;
adapter = new OleDbDataAdapter(query, conn);
adapter.Fill(ds);
int f = ds.Tables[0].Rows.Count;
int i;
for (i = 0; i < f; i++)
{
// create the database query
string query1 = "SELECT * FROM [time] Where classid= '"+
ds.Tables[0].Rows[i].ItemArray[2]+"'";
DataSet ds1 = new DataSet();
OleDbDataAdapter adapter1;
adapter1 = new OleDbDataAdapter(query1, conn);
adapter1.Fill(ds1);
MessageBox.Show(ds1.Tables[0].Rows[0].ItemArray[0].ToString());
}
the result that i get not true in message box that i want the id of all rows having the same classid but in message box that i use just to verification before o continue i see the id of time table without be consider where

Shouldn't this part be changed from...
string query1 = "SELECT * FROM [time] Where classid+ '"+
ds.Tables[0].Rows[i].ItemArray[2]+"'";
to...
string query1 = "SELECT * FROM [time] Where classid = '"+
ds.Tables[0].Rows[i].ItemArray[2]+"'";
You seem to be using a plus symbol (+) instead of equals (=).

Give this a shot:
public DataSet GetRelations()
{
using (var connection = new OleDbConnection(ConnectionString))
{
connection.Open();
using (var adapter = new OleDbDataAdapter("SELECT * FROM [relation]", connection))
{
var results = new DataSet();
adapter.Fill(results);
return results;
}
}
}
public DataSet GetTimeResults()
{
DataSet dsRelations = GetRelations();
var dsResults = new DataSet();
using (var connection = new OleDbConnection(ConnectionString))
{
connection.Open();
foreach (DataRow row in dsRelations.Tables[0].Rows)
{
using (var command = new OleDbCommand("SELECT * FROM [time] Where classid = ?", connection))
{
// not entirey sure what the value of row.ItemArray[2] is ?
command.Parameters.Add(row.ItemArray[2]);
using (var adapter = new OleDbDataAdapter(command))
{
adapter.Fill(dsResults);
}
}
}
}
return dsResults;
}
Just invoke it and use it as you see fit:
public void Test()
{
DataSet dsTimeResults = GetTimeResults();
// Do whatever you need with the results
}

Related

C# Paginate SQL result from a proc call

I have the following method that calls a proc in my database and returns the results into a dataset. The dataset is then used to populate a table I render using MVC & cshtml.
The method is:
public DataSet CallProcToDataSet(string procName)
{
DataSet ds = new DataSet();
string constr = ConfigurationManager.ConnectionStrings["UAT"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand(procName))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Connection = con;
using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
{
sda.Fill(ds);
}
}
}
return ds;
}
This works fine, however what I want is to have some way of paginating the results so that only 10 at a time are displayed. What is the best way for me to achieve this that doesn't involve any changes to the proc calls?
You can use this overload of the Fill method
public int Fill(int startRecord, int maxRecords, params DataTable[] dataTables);
(link: https://msdn.microsoft.com/en-us/library/0z5wy74x(v=vs.110).aspx)
This way you will only return a subset of the records without modifying your stored procedure.
Example (MSTest)
[TestMethod]
public void TestMethod1()
{
DataSet ds = new DataSet();
var procName = "sp_server_info";
string constr = ConfigurationManager.ConnectionStrings["UAT"].ConnectionString;
var tblName = "result";
var tbls = new[] { ds.Tables.Add(tblName) };
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand(procName))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Connection = con;
using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
{
sda.Fill(0, 10, tbls);
}
}
}
Assert.AreEqual(tbls[0].Rows.Count, 10);
}
Try following :
DataSet ds = new DataSet();
DataTable dt = ds.Tables[0];
for (int i = 0; i < dt.Rows.Count; i += 10)
{
DataTable pageTable = dt.AsEnumerable().Where((x, n) => (n >= i) && (n < i + 10)).CopyToDataTable();
}

Insert two data in different row with same id in another data

I have problem in inserting two data in different row with same id in another data;
in my DAL:
public DataTable test(string name, string course)
{
string insertsql = "INSERT INTO Table1(schName) OUTPUT INSERTED.addID values (#schName)";
SqlCommand cmd = new SqlCommand(insertsql,conn);
cmd.Parameters.AddWithValue("#schName", name);
conn.Open();
var table1Id = (int)cmd.ExecuteScalar();
string insertsql1 = "INSERT INTO Table2(ScholarshipID,DiplomaCourse) values (#id,#course)";
SqlCommand cmd2 = new SqlCommand(insertsql1, conn);
cmd2.Parameters.AddWithValue("#id", table1Id);
cmd2.Parameters.AddWithValue("#course", course);
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = cmd;
da.SelectCommand = cmd2;
DataTable dt = new DataTable();
da.Fill(dt);
conn.Close();
return dt;
}
in my codebehind(cs)
protected void Button1_Click(object sender, EventArgs e)
{
// addScholarship[] test = new addScholarship[1];
string course = "";
string name = schName.Text;
scholarshipBLL obj = new scholarshipBLL();
List<addScholarship> addScholarshipList = new List<addScholarship>();
addScholarship scholarship;
if (DIT.Checked )
{
scholarship = new addScholarship(name, course);
addScholarshipList.Add(scholarship);
course = "DIT";
DataTable dt = obj.test(name, course);
}
if (DFI.Checked)
{
scholarship = new addScholarship(name, course);
addScholarshipList.Add(scholarship);
course = "DFI";
DataTable dt = obj.test(name, course);
}
}
so there will be two checkboxes. right now it currently works if the user clicks on one checkbox. when the user clicks both checkboxes, it will give error such as:
System.InvalidOperationException: The connection was not closed. The connection's current state is open.
now i have closed it. once i click submit, it will insert twice.
table1
id schName
1 hi
2 hi
table 2
tableId id course
1 1 dfi
2 2 dit
where it should be like
table1
id schName
1 hi
table2
tableId Id course
1 1 dfi
2 1 dit
Again your are not thinking logically. It is obvious that you are adding rows into both table1 and table2 in test method. So if you call this method two times it will add rows in to both tables two times.
If you want to add only row in table1 then you should create a separate method for that and call it only once. And you should create another method to add rows in table2 and you should call it from the if block.
Following are the tow methods you need to have in scholarshipBLL class.
public int AddSholarship(string scholarshipName)
{
using(var conn = new SqlConnection(....))
{
string insertsql = "INSERT INTO Table1(schName) OUTPUT INSERTED.addID values (#schName)";
SqlCommand cmd = new SqlCommand(insertsql,conn);
cmd.Parameters.AddWithValue("#schName", name);
var table1Id = (int)cmd.ExecuteScalar();
return table1Id;
}
}
public DataTable AddCourse(string scholarshipId, string courseName)
{
using(var conn = new SqlConnection(....))
{
string insertsql1 = "INSERT INTO Table2(ScholarshipID,DiplomaCourse) values (#id,#course)";
SqlCommand cmd2 = new SqlCommand(insertsql1, conn);
cmd2.Parameters.AddWithValue("#id", scholarshipId);
cmd2.Parameters.AddWithValue("#course", courseName);
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = cmd2;
DataTable dt = new DataTable();
da.Fill(dt);
conn.Close();
return dt;
}
}
And button_Click Code should be changed as following.
string course = "";
string scholarshipName = schName.Text;
scholarshipBLL obj = new scholarshipBLL();
List<addScholarship> scholarshipList = new List<addScholarship>();
var scholarshipId = obj.AddSholarship(scholarshipName);
addScholarship scholarship;
if (DIT.Checked )
{
scholarship = new addScholarship(Name,course);
scholarshipList.Add(scholarship);
course = "DIT";
DataTable dt = obj.AddCourse(scholarshipId, course);
}
if (DFI.Checked)
{
scholarship = new addScholarship(Name,course);
scholarshipList.Add(scholarship);
course = "DFI";
DataTable dt = obj.AddCourse(scholarshipId, course);
}
You should wrap your connection object in a using statement. Then the compiler will take care what should be done.
public DataTable test(string name, string course)
{
using(var conn = new SqlConnection(....))
{
string insertsql = "INSERT INTO Table1(schName) OUTPUT INSERTED.addID values (#schName)";
cmd.Parameters.AddWithValue("#schName", name);
conn.Open();
var table1Id = (int)cmd.ExecuteScalar();
string insertsql1 = "INSERT INTO Table2(ScholarshipID,DiplomaCourse) values (#id,#course)";
cmd2.Parameters.AddWithValue("#id", table1Id);
cmd2.Parameters.AddWithValue("#course", course);
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = cmd;
da.SelectCommand = cmd2;
DataTable dt = new DataTable();
da.Fill(dt);
return dt;
}
}

Issue while deleting row using DataSet

Following code does not delete a row from dataset and dont update the database....
string cs = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
SqlConnection con = new SqlConnection();
con.ConnectionString = cs;
SqlDataAdapter adpt = new SqlDataAdapter("Select *from RegisterInfoB", con);
ds = new DataSet();
adpt.Fill(ds, "RegisterTable");
foreach (DataRow dr in ds.Tables[0].Rows)
{
if (dr["FirstName"] == "praveen")
{
dr.Delete();
}
}
ds.Tables[0].AcceptChanges();
How to resolve this problem...How do I update my sql server database...by deleting a row from dataset..
I hope this will work for you:
string cs = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
SqlConnection con = new SqlConnection();
con.ConnectionString = cs;
SqlDataAdapter adpt = new SqlDataAdapter("Select * from RegisterInfoB", con);
DataSet ds = new DataSet();
adpt.Fill(ds, "RegisterTable");
foreach (DataRow dr in ds.Tables[0].Rows)
{
if (dr["FirstName"].ToString().Trim() == "praveen")
{
dr.Delete();
}
}
adpt.Update(ds);
Two Changes
1st: if (dr["FirstName"].ToString().Trim() == "praveen") trimming the blank spaces in your db's FirstName Field.
2nd : use adpt.Update(ds); to update your DB.
Another Way to doing it:
string cs = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
SqlConnection con = new SqlConnection();
con.ConnectionString = cs;
string firstName= "praveen"; // this data will get from calling method
SqlDataAdapter adpt = new SqlDataAdapter("Select * from RegisterInfoB", con);
DataSet ds = new DataSet();
adpt.Fill(ds, "RegisterTable");
string deleteQuery = string.Format("Delete from RegisterInfoB where FirstName = '{0}'", firstName);
SqlCommand cmd = new SqlCommand(deleteQuery, con);
adpt.DeleteCommand = cmd;
con.Open();
adpt.DeleteCommand.ExecuteNonQuery();
con.Close();
Similary, you can write query for UpdateCommand and InsertCommand to perform Update and Insert Respectively.
Find rows based on specific column value and delete:
DataRow[] foundRows;
foundRows = ds.Tables["RegisterTable"].Select("FirstName = 'praveen'");
foundRows.Delete();
EDIT: Adding a DeleteCommand to the data adapter (based on example from MSDN)
Note: Need an Id field here instead of FirstName, but I don't know your table structure for RegisterInfoB. Otherwise, we delete everyone named "praveen".
// Create the DeleteCommand.
command = new SqlCommand("DELETE FROM RegisterInfoB WHERE FirstName = #FirstName", con);
// Add the parameters for the DeleteCommand.
parameter = command.Parameters.Add("#FirstName", SqlDbType.NChar, 25, "FirstName");
parameter.SourceVersion = DataRowVersion.Original;
// Assign the DeleteCommand to the adapter
adpt.DeleteCommand = command;
To update a database with a dataset using a data adapter:
try
{
adpt.Update(ds.Tables["RegisterTable"]);
}
catch (Exception e)
{
// Error during Update, add code to locate error, reconcile
// and try to update again.
}
Sources: https://msdn.microsoft.com/en-us/library/xzb1zw3x(v=vs.120).aspx
https://msdn.microsoft.com/en-us/library/y06xa2h1(v=vs.120).aspx
hope that resolve the problem,
Try it:
var connectionString = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
var selectQuery = "Select * from RegisterInfoB";
SqlConnection connection = new SqlConnection(connectionString);
SqlCommand selectCommand = new SqlCommand(selectQuery, connection);
SqlDataAdapter adapter = new SqlDataAdapter(selectCommand);
SqlCommandBuilder builder = new SqlCommandBuilder(adapter);
DataSet dataSet = new DataSet();
// you can use the builder to generate the DeleteCommand
adapter.DeleteCommand = builder.GetDeleteCommand();
// or
// adapter.DeleteCommand = new SqlCommand("DELETE FROM RegisterInfoB WHERE Id= #Id", connection);
adapter.Fill(dataSet, "RegisterInfoB");
// you can use the foreach loop
foreach (DataRow current in dataSet.Tables["RegisterInfoB"].Rows)
{
if (current["FirstName"].ToString().ToLower() == "praveen")
{
current.Delete();
}
}
// or the linq expression
// dataSet.Tables["RegisterInfoB"]
// .AsEnumerable()
// .Where(dr => dr["FirstName"].ToString().ToLower().Trim() == "praveen")
// .ToList()
// .ForEach((dr)=> dr.Delete());
var result = adapter.Update(dataSet.Tables["RegisterInfoB"]);
also you can add some events and put a breakpoint to see if the state is changing or if there is an error that prevent changes on the source:
dataSet.Tables["RegisterInfoB"].RowDeleted += (s, e) =>
{
var r = e.Row.RowState;
};
dataSet.Tables["RegisterInfoB"].RowDeleting += (s, e) =>
{
var r = e.Row.RowState;
};

How to count the number of rows from sql table in c#?

How to count the number of rows from sql table in c#?
I need to extract some data from my database...
You may try like this:
select count(*) from tablename where columname = 'values'
C# code will be something like this:-
public int A()
{
string stmt = "SELECT COUNT(*) FROM dbo.tablename";
int count = 0;
using(SqlConnection thisConnection = new SqlConnection("Data Source=DATASOURCE"))
{
using(SqlCommand cmdCount = new SqlCommand(stmt, thisConnection))
{
thisConnection.Open();
count = (int)cmdCount.ExecuteScalar();
}
}
return count;
}
You need to make a database connection from c# first. Then, you need to pass below query as commandText.
Select count(*) from TableName
Use ExecuteScalar/ExecuteReader to get the returned count.
Do you means likes this ?
SELECT COUNT(*)
FROM yourTable
WHERE ....
You can make global function that you can use all the time as
public static int GetTableCount(string tablename, string connStr = null)
{
string stmt = string.Format("SELECT COUNT(*) FROM {0}", tablename);
if (String.IsNullOrEmpty(connStr))
connStr = ConnectionString;
int count = 0;
try
{
using (SqlConnection thisConnection = new SqlConnection(connStr))
{
using (SqlCommand cmdCount = new SqlCommand(stmt, thisConnection))
{
thisConnection.Open();
count = (int)cmdCount.ExecuteScalar();
}
}
return count;
}
catch (Exception ex)
{
VDBLogger.LogError(ex);
return 0;
}
}
This works for me
using (var context = new BloggingContext())
{
var blogs = context.Blogs.SqlQuery("SELECT * FROM dbo.Blogs").ToList();
}
For more information consult: https://learn.microsoft.com/es-es/ef/ef6/querying/raw-sql?redirectedfrom=MSDN
Use this its working
string strQuery = "SELECT * FROM staff WHERE usertype='lacturer'";
connect.Open();
SqlCommand cmd = new SqlCommand(strQuery, connect);
SqlDataAdapter OleDbDa = new SqlDataAdapter(cmd);
DataSet dsData = new DataSet();
OleDbDa.Fill(dsData);
connect.Close();
std.Text = dsData.Tables[0].Rows.Count.ToString();
I used this method in my own application to count the number of active users within the program. This can be easily manipulated for your own use.
con.open();
string ActiveUsers = "SELECT * FROM Devices WHERE Status='" + "Online" + "'";
SqlCommand cmd = new SqlCommand(ActiveUsers, con);
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
sda.Fill(ds);
con.Close();
Users.Text = ds.Tables[0].Rows.Count.ToString();

How to pass dataset through query

I need to get a database values to the p_cat combo box .....but i cannot pass the dataset inside the query..
class Datatbl_Class1
{
DataSet ds = new DataSet();
public DataSet filldata(string q)
{
string myconnection = "datasource=localhost;port=3306;username = root; password = 12345V";
MySqlConnection con = new MySqlConnection(myconnection);
MySqlCommand cmd = new MySqlCommand(q, con);
MySqlDataAdapter da = new MySqlDataAdapter(cmd);
da.Fill(ds);
return ds;
}
}
Select_int_Class1 s4 = new Select_int_Class1();
string q = "SELECT Sup_ID FROM gtec_computer.supplier WHERE Sup_Name='" +p_cmb_sup.Text+ "'";
string ww = "Sup_ID";
int t = s4.select_val_int(q, ww);
DataSet n = new DataSet();
Datatbl_Class1 dt = new Datatbl_Class1();
string Query = "SELECT Cat_ID FROM gtec_computer.supplier_detail WHERE Sup_Id="+t+" ";
n = dt.filldata(Query)
DataSet ds = new DataSet();
string myconnection = "datasource=localhost;port=3306;username = root; password = 12345V";
MySqlConnection con = new MySqlConnection(myconnection);
string q1 = "SELECT cat_Name FROM gtec_computer.category WHERE Cat_ID= " + n + " ";
MySqlCommand cmd = new MySqlCommand(q1, con);
MySqlDataAdapter da1 = new MySqlDataAdapter(cmd);
da1.Fill(ds);
p_cat.DataSource = ds;
You should be able to via parameter to the function call in the class... However, by building your command strings, you would be wide open for SQL-injection. Look into parameterized queries. Now, back to your original code and an alternative implementation...
class Datatbl_Class1
{
public DataSet filldata(string q )
{
string myconnection = "datasource=localhost;port=3306;username = root; password = 12345V";
MySqlConnection con = new MySqlConnection(myconnection);
MySqlCommand cmd = new MySqlCommand(q, con);
MySqlDataAdapter da = new MySqlDataAdapter(cmd);
DataSet ReturnThisOne = new DataSet();
da.Fill(ReturnThisOne);
return ReturnThisOne;
}
}
Just dont make the "ds" as a property of the class. Just create a new instance of a dataset within your method. It will be a pointer anyhow. Fill that and return the pointer to the calling source as you already are doing with your "n = dt.filldata(Query)". Yes, the function is no longer using the data table, but since it's reference is being returned, then the "n" location that is calling it will retain it. It won't get released to garbage collection until the function that "n" is in gets released.
Again, look into parameters to prevent sql-injection. But this should get you going.

Categories

Resources