sqldataAdapter in Csharp in easier way? - database

I am new to Model view Controller so i wanna know what's the exact meaning of data Adapter. I used to create procedure but after that in my controller i use object of sql command and then by using adapter i fetch data's of tables that exists in database.
public void ExecuteSelectQueryWithDataTable(String procedureName, SqlParameter[] sqlParameter, out DataTable dataTable)
{
dataTable = new DataTable();
Random Rnd = new Random();
try
{
using (SqlConnection sqlConnection = new SqlConnection(connectionstring))
{
using (SqlCommand sqlCommand = new SqlCommand("", sqlConnection))
{
using (SqlDataAdapter sqlDataAdapter = new SqlDataAdapter(sqlCommand))
{
sqlCommand.CommandText = procedureName;
sqlCommand.CommandType = CommandType.StoredProcedure;
sqlCommand.Parameters.AddRange(sqlParameter);
sqlDataAdapter.SelectCommand = sqlCommand;
sqlDataAdapter.Fill(dataTable);
}
}
}
}
Thanks in advance!

SQLDataAdaptor is one ado.net class that fill datatable by database table or result set of stored procedure.
I suggest to connect to DB by entity framework instead of legacy development.
BR

Related

Importing data from Excel into SQL Server that has a different design in the template in Excel

I am developing a system that will import and export a data from Excel into a SQL Server database. I already done in exporting, my problem is in importing the template that I will import is different template that I exported. I know the code about importing because I learned it in google, but in my problem is, I can't get what I need. So allow me to show a screenshot about the template in my Excel.
That's the template, and my database design is like this:
So the PODATE and PORECEIVEDDATE there in database is equal to the PO DATE below in Excel and DELIVERYDATE is equal to ETD in Excel.
As of now I have a code here that will get only the above template and it will not get the whole data in Excel.
Here is my code:
public void ImportDataFromExcel(string excelFilePath)
{
string ssqltable = "tmp_100_POEntry_SF_sample";
//string myexceldataquery = "select PONO,PODATE,PORECEIVEDDATE,DELIVERYDATE,PARTCODE,QUANTITY,UNITCOST,TOTALAMOUNT,STOCKS,INCHARGE,CLIENT from [Sheet1$]";
string myexceldataquery = "select [PO NO],[PART CODE],QUANTITY,[UNIT COST],[TOTAL AMOUNT],STOCKS,[IN CHARGE],CLIENT from [Sheet1$]";
try
{
string sexcelconnectionstring = #"provider=microsoft.jet.oledb.4.0;data source=" + excelFilePath +
";extended properties=" + "\"excel 8.0;hdr=yes;\"";
string sclearsql = "delete from " + ssqltable;
SqlConnection sqlconn = new SqlConnection(Common.connectionstring);
SqlCommand sqlcmd = new SqlCommand(sclearsql, sqlconn);
sqlconn.Open();
sqlcmd.ExecuteNonQuery();
sqlconn.Close();
OleDbConnection oledbconn = new OleDbConnection(sexcelconnectionstring);
OleDbCommand oledbcmd = new OleDbCommand(myexceldataquery, oledbconn);
oledbconn.Open();
OleDbDataReader dr = oledbcmd.ExecuteReader();
SqlBulkCopy bulkcopy = new SqlBulkCopy(Common.connectionstring);
bulkcopy.DestinationTableName = ssqltable;
while (dr.Read())
{
bulkcopy.WriteToServer(dr);
}
dr.Close();
oledbconn.Close();
}
catch (Exception ex)
{ throw ex; }
}
That code is really have an error if I add the PODATE, PORECEIVEDDATE and DELIVERDATE. All I just want is to get the 3 remaining parameters value from Excel into the database.
I don't want to change the template in Excel because of some reason.
Please I badly need your help guys. I really appreciate it.

The connection was not closed the connection current state is open

Hye... I currently doing my final year project using vb.net and i got this error. Im tryin' to fix the error but still not succeed. I use ms access for database in my project. I try to put con.Open() before the 'dt' statement and con.Close() after the 'cboProduct.Select' but the result is the same. Really appreciate your helps. Thanks :)
'GLOBAL DECLARATIONS
Dim conString As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\Acer User\Documents\MAKLUMAT IVENTORI.accdb"
Dim con As OleDbConnection = New OleDbConnection(conString)
Dim adapter As New OleDbDataAdapter
Dim cmd As New OleDbCommand
Dim dt As New DataTable
Dim ds As New DataSet
Private Sub RefreshData()
dt = New DataTable
ds = New DataSet
ds.Tables.Add(dt)
adapter = New OleDbDataAdapter("Select * FROM product WHERE lab_kod='66'", con)
adapter.Fill(dt)
DataGridView1.DataSource = dt.DefaultView
labelID.Text = getAutoID()
lblLabCode.Text = "66"
cboProduct.Select()
Dim v_SQL As String = "SELECT * FROM kategori_product"
cmd = New OleDbCommand(v_SQL, con)
con.Open()
Dim v_dataReader As OleDbDataReader = cmd.ExecuteReader()
Dim v_dataTable As New DataTable
v_dataTable.Columns.Add("product_kod", Type.GetType("System.String"))
If v_dataReader.HasRows Then
While v_dataReader.Read
v_dataTable.Rows.Add(v_dataReader.GetString(0))
End While
cboProduct.DataSource = v_dataTable
End If
cboProduct.DisplayMember = "product_kod"
cboProduct.ValueMember = "product_kod"
v_dataReader.Close()
con.Close()
End Sub
Don't store short-lived objects, such as database connections, as global variables.
In fact, don't use global variables, ever, at all.
(though I note that assuming this is a Class and not a Module those are actually class fields, not globals, but you're still misusing them)
Your OleDbDataAdapter.Fill call requires the connection to be open, but you call .Fill(dt) before calling con.Open()
Use Using (using() in C#) blocks to ensure your database connection is always closed, even in the event of failure.

dropdownlist control in detailsview to database

I have a detailsview which is used for inserting new records to the GRIDVIEW. DetailsView has 3 bound fields and one template field. The template field has a dropdownlist control.
When I click insert, all the fields should be entered into the database. Bound fields get inserted, but I have problem with the dropdownlist control. I tried writing this code especially for dropdownlist in "INSERT" click event
protected void btnInsert_Click(object sender, EventArgs e)
{
DropDownList ddl = null;
ddl = new DropDownList();
RateCenters rate = null;
rate = new RateCenters();
rate.statename = ddl.Text;
OleDbConnection con = new OleDbConnection(conStr);
OleDbCommand cmd = new OleDbCommand(sql, con);
cmd.Parameters.Add("#State/Province_name", OleDbType.VarChar).Value = statename;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
I am getting this error : Parameter [State/Province_name] has no default value.
Kindly help me to solve this issue
regards,
Arjun
shouldn't you be using rate.statename
cmd.Parameters.Add("#State/Province_name", OleDbType.VarChar).Value = rate.statename;

Will a Winforms grid keep its datasource in memory? .Net

I've a grid in my winforms application and i bind a huge dataset to the grid. Will the dataset be stored in the memory by the grid after calling DataBind(). How does it operate on the data binded to the grid?
Update
I wrote the following code
DataTable dt = new DataTable();
using (SqlConnection con = new SqlConnection("Server=server;Initial Catalog=db;User ID=testv;Pwd=pass"))
{
con.Open();
using (SqlCommand com = new SqlCommand("select * from tbl_Sample", con))
{
using (SqlDataAdapter ada = new SqlDataAdapter(com))
{
ada.Fill(dt);
dgvMain.DataSource = dt;
dt.Dispose();
}
}
}
After assigning the datatable as the datasource i'm able to dispose it. So does it make a copy in the memory?
Thanks
NLV
It doesn't make a copy, it makes a reference to the original datasource object.
P.S. Making a huge dataset is not a good idea anyway. If you need to display lots of rows, make some kind of paging or filters and restrict number of rows to load and display.

How to import sql in vb.net?

I mean the imports keyword on the uppermost part of the program.
What should I type in there?
Imports System.Data
Imports System.Data.SqlClient
Then here's an example of how to talk to the db:
Using cn As New SqlConnection("connection string here"), _
cmd As New SqlCommand("Sql statements here")
cn.Open()
Using rdr As SqlDataReader = cmd.ExecuteReader()
While rdr.Read()
''# Do stuff with the data reader
End While
End Using
End Using
and a c# translation, because people were curious in the comments:
using (var cn = new SqlConnection("connection string here"))
using (var cmd = new SqlCommand("Sql statements here"))
{
cn.Open();
using (var rdr = cmd.ExecuteReader())
{
while (rdr.Read())
{
// Do stuff with the data reader
}
}
}
You mean:
Imports System.Data.SqlClient
Imports System.Data.SqlClient

Resources