I am using a SqlHelper class which has common methods for CRUD operations.
public static void Fill(DataSet dataSet, String procedureName)
{
SqlConnection oConnection = new SqlConnection(DBInterface.ConnectionString);
SqlCommand oCommand = new SqlCommand(procedureName, oConnection);
oCommand.CommandType = CommandType.StoredProcedure;
SqlDataAdapter oAdapter = new SqlDataAdapter();
oAdapter.SelectCommand = oCommand;
oConnection.Open();
using (SqlTransaction oTransaction = oConnection.BeginTransaction())
{
try
{
oAdapter.SelectCommand.Transaction = oTransaction;
oAdapter.Fill(dataSet);
oTransaction.Commit();
}
catch
{
oTransaction.Rollback();
throw;
}
finally
{
if (oConnection.State == ConnectionState.Open)
oConnection.Close();
oConnection.Dispose();
oAdapter.Dispose();
}
}
}
Now in my code, I am calling this method as,
private void BindCustomers()
{
DataSet dsCust = new DataSet();
SqlHelper.Fill(dsCust, "getCustomers");
--then I bind this dataset to datagridview
}
This all works fine. Now I want to update the data in the database. But I am confused how do I call DataAdatpaer.Update(dataset) here to update the changes made in datagridview into database. Is this possible here? Or I need to do it conventionally to find the updated row and call the ExecuteNonQuery function in the SqlHelper? Is there anything which can be done to use dataadapter.update(ds)
Thanks
You don't need to hide data adapter, or if for any reason you did so, you need to expose a method in your class to push updates to server.
Example
Public class SqlHelper
{
string commandText;
string connectionString;
public SqlHelper(string command, string connection)
{
commandText = command;
connectionString = connection;
}
public DataTable Select()
{
var table = new DataTable();
using (var adapter = new SqlDataAdapter(this.commandText, this.connectionString))
adapter.Fill(table)
return table;
}
public void Update(DataTable table)
{
using (var adapter = new SqlDataAdapter(this.commandText, this.connectionString))
{
var builder = new SqlCommandBuilder(adapter);
adapter.Update(table);
}
}
}
By calling this method in your code you can perform all crud operation select, update, delete and insert. you just need to pass connection string, procedure name and parameters list. Using this method you will retrieve data in the DataTable.if anyone want Dataset(Multiple Result) then just need to replace DataSet on the place of DataTable
SqlConnection conn = new SqlConnection("Your ConnectionString");
public DataTable ExecuteDataTable(string ProcedureName, SqlParameter[] _Param)
{
try
{
DataTable dataTable = new DataTable();
SqlCommand cmd = new SqlCommand(ProcedureName, conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Clear();
if (_Param is not null)
{
for (int i = 0; i < _Param.Length; i++)
{
if (_Param[i].ParameterName is not null)
{
if (_Param[i].Value is not null)
{
cmd.Parameters.AddWithValue(_Param[i].ParameterName, _Param[i].Value);
}
else
{
cmd.Parameters.AddWithValue(_Param[i].ParameterName, DBNull.Value);
}
}
}
}
conn.Open();
SqlDataAdapter DA = new SqlDataAdapter(cmd);
DA.Fill(dataTable);
conn.Close();
return dataTable;
}
catch (Exception ex)
{
conn.Close();
throw;
}
}
Related
I want to display data in a datagrid based on value selected in a ComboBox but my datatable function returns null and nothing is displayed in the datagrid.
public DataTable ReadData(User user)
{
using (SqlConnection db = new SqlConnection(AppConnect.Connection))
{
string query = "SELECT moduleCode,moduleName,modCredits,modHrsLeft FROM [Module] WHERE userName=#userName";
try
{
using (SqlCommand command = new SqlCommand(query, db))
{
if (db.State == ConnectionState.Closed)
{
db.Open();
command.Parameters.AddWithValue("#userName", user.UserName);
SqlDataAdapter dataAdapter = new SqlDataAdapter(command);
table = new DataTable();
dataAdapter.Fill(table);
}
}
db.Close();
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
return table;
}
}
This function is in a class library. The function is called in the WPF project, this is the code:
private void BtnDisplay_Click(object sender, RoutedEventArgs e)
{
string userName = CmboxUserN.SelectedItem.ToString();
User user1 = new User
{
UserName = userName
};
DataTable table = data.ReadData(user1);
gridModules.DataContext= table;
}
Try these changes. It seems that the line table = new DataTable(); is never being hit. You don't need to check to make sure the connection is in a closed state because you are using a using statement.
public DataTable ReadData(User user)
{
using (SqlConnection db = new SqlConnection(AppConnect.Connection))
{
string query = "SELECT moduleCode,moduleName,modCredits,modHrsLeft FROM [Module] WHERE userName=#userName";
try
{
using (SqlCommand command = new SqlCommand(query, db))
{
db.Open();
command.Parameters.AddWithValue("#userName", user.UserName);
SqlDataAdapter dataAdapter = new SqlDataAdapter(command);
table = new DataTable();
dataAdapter.Fill(table);
}
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
return table;
}
}
Also, you don't need to .Close() the connection because the SqlConnection is in a using statement, which means the object will be disposed of when the scope of the using statement is exited.
One other tip: You should change the code to have the try catch around everyting and if there are any errors at all, log the errors to console and return a new DataTable().
I am trying to execute a stored procedure with parameters, and get the results into a DataTable; but after execution, I get this:
this is the screen
I can get IDataRecord but I can't IDataReader - why? What do I miss? Thanks
public DataTable ExecuteProcedureTest(string storedProcedure, Dictionary<Filter, object> filterValue)
{
var parameters = GetParams(filterValue);
var sqlConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["testconn"].ConnectionString);
var cmd = sqlConnection.CreateCommand();
SqlDataReader reader;
IDataReader dataReader;
IDataRecord[] dataRecords;
var table = new DataTable();
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = storedProcedure;
foreach (var item in parameters)
{
cmd.Parameters.Add(item);
}
try
{
sqlConnection.Open();
reader = cmd.ExecuteReader();
dataRecords = reader.OfType<IDataRecord>().ToArray();
table.Load(reader);
}
catch (Exception ex)
{
throw ex;
}
finally
{
sqlConnection.Dispose();
}
//var count = dataRecords.Count();
return table;
}
If your goal is to fill a DataTable from a SqlCommand, use a SqlDataAdapter instead of a SqlDataReader. Here is a handy extension method:
public static class SqlExtensions
{
public static DataTable ExecuteDataTable(this SqlCommand command)
{
DataTable table = new DataTable();
using (SqlDataAdapter dataAdapter = new SqlDataAdapter(command))
{
dataAdapter.Fill(table);
}
return table;
}
}
Then from your code you can use it like this:
try
{
sqlConnection.Open();
table = cmd.ExecuteDataTable();
}
finally
{
sqlConnection.Dispose();
}
private void button1_Click(object sender, EventArgs e)
{
try
{
SqlConnection conn = new SqlConnection();
conn.ConnectionString = "Data Source=*******;Initial Catalog=ChatApp;User ID=Chatapplication;Password=****";
conn.Open();
SqlCommand cmd = new SqlCommand();
string chatroomidno = textBox1.Text;
string chatroomname = textBox2.Text;
//cmd.CommandText = "Select ChatRoomID=#ChatRoomID,ChatRoomName=#ChatRoomName from tblChatRoom";
//cmd.Connection = conn;
SqlDataAdapter adapt = new SqlDataAdapter("Chatroomapp",conn);
adapt.SelectCommand.CommandType = CommandType.StoredProcedure;
DataSet ds=new DataSet();
DataTable dt = new DataTable();
adapt.SelectCommand.Parameters.Add(new SqlParameter("#ChatRoomID", SqlDbType.VarChar, 100));
adapt.SelectCommand.Parameters["#ChatRoomID"].Value = chatroomidno;
adapt.SelectCommand.Parameters.Add(new SqlParameter("#ChatRoomName", SqlDbType.VarChar, 50));
adapt.SelectCommand.Parameters["#ChatRoomName"].Value = chatroomname;
adapt.Fill(ds, "tblChatRoom");
if (dt.Rows.Count > 0)
{
MessageBox.Show("Connection Succedded");
}
else
{
MessageBox.Show("Connection Fails");
}
}
catch (Exception ex)
{
MessageBox.Show("Error", ex.Message);
}
}
While compiling the program I got only connection fails message box, in the database. I found correct, how to overcome the program to get the connection succeeded message box.
Well, you're filling the ds data set - but then you're checking the dt data table for presence of rows... that's never going to work, of course!
If you only need a single DataTable - just use and fill that data table alone - no need for the overhead of a DataSet. Also, put your SqlConnection and SqlCommand into using blocks like this:
using (SqlConnection conn = new SqlConnection("Data Source=*******;Initial Catalog=ChatApp;User ID=Chatapplication;Password=****"))
using (SqlCommand cmd = new SqlCommand("Chatroomapp", conn))
{
string chatroomidno = textBox1.Text;
string chatroomname = textBox2.Text;
SqlDataAdapter adapt = new SqlDataAdapter(cmd);
adapt.SelectCommand.CommandType = CommandType.StoredProcedure;
adapt.SelectCommand.Parameters.Add(new SqlParameter("#ChatRoomID", SqlDbType.VarChar, 100));
adapt.SelectCommand.Parameters["#ChatRoomID"].Value = chatroomidno;
adapt.SelectCommand.Parameters.Add(new SqlParameter("#ChatRoomName", SqlDbType.VarChar, 50));
adapt.SelectCommand.Parameters["#ChatRoomName"].Value = chatroomname;
// fill the data table - no need to explicitly call `conn.Open()` -
// the SqlDataAdapter automatically does this (and closes the connection, too)
DataTable dt = new DataTable();
adapt.Fill(dt);
if (dt.Rows.Count > 0)
{
MessageBox.Show("Connection Succedded");
}
else
{
MessageBox.Show("Connection Fails");
}
}
And just because you get back no rows in dt.Rows doesn't necessarily mean that your connection failed..... it could just be that there are no rows that match your search critieria! The connection worked just fine - but the SQL command just didn't return any rows.
Connection failed means that something went wrong between your program and the database. No records returned does not mean that the connection failed. It just means that your table is empty - it contains no records.
Using ADO.NET and a stored procedures would have been a little different from what you have done it. If you need to check if the connection failed, maybe it is better to check the type of exception that is returned in the catch part.
Below is how I would have done it. I would have created a separate method that would have handled my call, and then in your button1_Click I would have just called this method:
public async Task<ChatRoom> GetAsync(string chatRoomId, string chatRoomName)
{
try
{
string connectionString = ConfigurationManager.ConnectionStrings["Db"].ConnectionString;
using (SqlConnection sqlConnection = new SqlConnection(connectionString))
{
await sqlConnection.OpenAsync();
using (SqlCommand sqlCommand = new SqlCommand("ChatRooms_Get", sqlConnection))
{
sqlCommand.CommandType = CommandType.StoredProcedure;
sqlCommand.Parameters.Add(new SqlParameter("#ChatRoomID", chatRoomId));
sqlCommand.Parameters.Add(new SqlParameter("#ChatRoomName", chatRoomName));
using (SqlDataReader sqlDataReader = await sqlCommand.ExecuteReaderAsync())
{
ChatRoom chatRoom = null;
if (await sqlDataReader.ReadAsync())
{
chatRoom = new ChatRoom();
chatRoom.Id = sqlDataReader.GetFieldValue<string>(0);
chatRoom.Name = sqlDataReader.GetFieldValue<string>(1);
chatRooms.Add(chatRoom);
}
return chatRoom;
}
}
}
}
catch (Exception exception)
{
// Try checking if the connection failed here
throw exception;
}
}
My chat room domain model could have looked like this:
public class ChatRoom
{
public string Id { get; set; }
public string Name { get; set; }
}
And the stored procedure would have looked like this:
CREATE PROCEDURE [dbo].[ChatRooms_Get]
(
#ChatRoomID VARCHAR(100),
#ChatRoomName VARCHAR(50)
)
AS
BEGIN
SET NOCOUNT ON;
SELECT
ChatRoomID,
ChatRoomName
FROM
tblChatRoom
WHERE
ChatRoomID = #ChatRoomID
AND ChatRoomName = #ChatRoomName;
END
GO
And then in the calling method you would get the chatroom and do with it whatever you need to do with it. For this example I just checked if it exists or not:
try
{
ChatRoom chatRoom = await chatRoomRepository.GetAsync(chatRoomId, chatRoomName);
if (chatRoom != null)
{
MessageBox.Show("Record found");
}
else
{
MessageBox.Show("No record found");
}
}
catch (Exception exception)
{
throw exception;
}
I hope this can help.
I have a homework about database connection via ms access.
I prepared my database and saved it as dbMert and put it to debug / bin
This is my CustomerDatabase class for connecting to database:
static class CustomerDatabase
{
static string connectionstring = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=dbMert.mdb";
static OleDbConnection connection = null;
static OleDbCommand command = null;
public static void ConnectToDatabase()
{
if (connection == null)
{
connection = new OleDbConnection(connectionstring);
command = new OleDbCommand();
command.Connection = connection;
command.CommandText = "select * from Customer";
}
}
public static DataTable executeSelect(string sql)
{
ConnectToDatabase();
DataTable dt = null;
dt = new DataTable();
command.CommandText = sql;
OpenConnection();
OleDbDataReader datareader = command.ExecuteReader();
dt.Load(datareader);
datareader.Close();
CloseConnection();
return dt;
}
public static void OpenConnection()
{
try
{
if (connection != null)
{
connection.Open();
}
}
catch (Exception ex)
{
}
}
public static void CloseConnection()
{
if (connection != null)
{
connection.Close();
}
}
}
}
Form: In constructor i try to connect to database
public Form1()
{
InitializeComponent();
CustomerDatabase.ConnectToDatabase();
}
and in form's load i try to take tuples to datagridview but nothing happens :S
private void Form1_Load(object sender, EventArgs e)
{
string sql1 = "select * from Customer";
DataTable dt = CustomerDatabase.executeSelect(sql1);
}
Regardless of other things (such as not keeping a single connection open, using using statements etc) you're not connecting your newly-loaded DataTable to your DataGridView at all. Your Form1_Load method just loads the data into a DataTable, then effectively throws it away.
I suspect you want something like:
dataGridView.DataSource = dt;
at the end of the method.
EDIT: Note that this is also a really bad idea in your OpenConnection code:
catch (Exception ex)
{
}
That basically says, "If something goes wrong, don't bother recording that fact or changing how the rest of the code works - just keep going as if nothing had happened."
Why are you catching the exception at all?
Try to write simple code. I suggest you to use OleDbDataAdaper, its Fill() method populate the DataTable easily.
You may use |DataDirectory| if you are using database (.mdb) located under Bin\Debug folder.
static string connectionstring = #"Provider=Microsoft.ACE.OLEDB.12.0;
Data Source=|DataDirectory|\dbMert.mdb";
Or
static string connectionstring = #"Provider=Microsoft.ACE.OLEDB.12.0;
Data Source=x:\full_path\dbMert.mdb";
Or
static string connectionstring = #"Provider=Microsoft.Jet.OLEDB.4.0;
Data Source=x:\full_path\dbMert.mdb";
static class Test
{
static string connectionstring = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=dbMert.mdb";
public static DataTable executeSelect(string sql)
{
DataTable dt = new DataTable();
OleDbDataAdapter adapter = new OleDbDataAdapter(sql,connectionString);
adapter.Fill(dt);
return dt;
}
}
Add following code in form_load handler,
string sql1 = "select * from Customer";
DataTable dt = Test.executeSelect(sql1);
DataGridView1.DataSource=dt;
When I move the DB-file to bin/debug, an error message states "4.0 is not installed".
However, when I move it to bin, the problem is solved.
My code:
con.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0; Data Source= ..\\dbMert.mdb";
con.Open();
recordları
DataSet ds = new DataSet();
DataTable dt = new DataTable();
ds.Tables.Add(dt);
OleDbDataAdapter da = new OleDbDataAdapter();
da = new OleDbDataAdapter("Select * from Customer", con);
da.Fill(dt);
dataGridView1.DataSource = dt;
foreach (DataRow row in dt.Rows)
{
foreach (DataColumn col in dt.Columns)
if(col.ToString() == "emailAdress")
comboBox1.Items.Add(row[col]);
}
con.Close();
public DataTable UserUpdateTempSettings(int install_id, int install_map_id, string Setting_value,string LogFile)
{
SqlConnection oConnection = new SqlConnection(sConnectionString);
DataSet oDataset = new DataSet();
DataTable oDatatable = new DataTable();
SqlDataAdapter MyDataAdapter = new SqlDataAdapter();
try
{
oConnection.Open();
cmd = new SqlCommand("SP_HOTDOC_PRINTTEMPLATE_PERMISSION", oConnection);
cmd.Parameters.Add(new SqlParameter ("#INSTALL_ID", install_id));
cmd.Parameters.Add(new SqlParameter ("#INSTALL_MAP_ID", install_map_id));
cmd.Parameters.Add(new SqlParameter("#SETTING_VALUE", Setting_value));
if (LogFile != "")
{
cmd.Parameters.Add(new SqlParameter("#LOGFILE",LogFile));
}
cmd.CommandType = CommandType.StoredProcedure;
MyDataAdapter.SelectCommand = cmd;
cmd.ExecuteNonQuery();
MyDataAdapter.Fill(oDataset);
oDatatable = oDataset.Tables[0];
return oDatatable;
}
catch (Exception ex)
{
Utils.ShowError(ex.Message);
return oDatatable;
}
finally
{
if ((oConnection.State != ConnectionState.Closed) || (oConnection.State != ConnectionState.Broken))
{
oConnection.Close();
}
oDataset = null;
oDatatable = null;
oConnection.Dispose();
oConnection = null;
}
}
I have used ExecuteNonQuery above. Normally it's not used with SqlDataAdapter. If I do not use it, I get an error.
Is it bad programming practice to use ExecuteNonQuery with SqlDataAdapter?
Hi deepti you don't have to call executeNonQuery because the fill method of the dataadapter is taking care for you. Here is a small sample:
using System.Data;
using System.Data.SqlClient;
using System.Windows.Forms;
namespace WindowsFormsApplication9
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
FillData();
}
void FillData()
{
// 1
// Open connection
using (SqlConnection c = new SqlConnection(
Properties.Settings.Default.DataConnectionString))
// 2
// Create new DataAdapter
using (SqlDataAdapter a = new SqlDataAdapter("SELECT * FROM EmployeeIDs", c))
{
// 3
// Use DataAdapter to fill DataTable
DataTable t = new DataTable();
a.Fill(t);
// 4
// Render data onto the screen
// dataGridView1.DataSource = t; // <-- From your designer
}
}
}
}
I don't think it's a matter of bad practice, it just doesn't make sense to do it in this situation. The fill method is used to populate the results from a select command. ExecuteNonQuery() is normally used when you're not retrieving data, and will only return the number of results.
You can find more about the fill method here