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
Related
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
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.
I'm slowly transitioning to VB.Net and it seems like the simplest of things are completely different. I'm trying to do a connection to SQL Server and just grab some data. I've tested the connection and it's fine. Now I'm trying to simply select some data from the server and display the first name in the Msgbox (or anything for that matter). Here is the code I've gotten so far....
Imports System.Data
Imports System.Data.SqlClient
Public Class Form1
Public conn As New SqlConnection("data source=Tuys1;initial catalog=DDDBuyer; user ID=userID; password=password")
Private dA As New SqlDataAdapter("Select FirstName, LastName from tblBuyers where Buyerid=1473", conn)
Private dS As New DataSet
End Class
I'm not really sure how to go from here... I understand there is something like
.hasRows
if ds.hasrows then
msgbox = "HELLO"
End if
or something like displaying the FirstName in txtFirstName
I am trying to get an idea of how ths works and after some research it's hard to find a specific example that would help me do what I'm trying to accomplish.
Dim custAdapter As SqlDataAdapter = New SqlDataAdapter( _
"SELECT * FROM dbo.Customers", customerConnection)
Dim ordAdapter As OleDbDataAdapter = New OleDbDataAdapter( _
"SELECT * FROM Orders", orderConnection)
Dim customerOrders As DataSet = New DataSet()
custAdapter.Fill(customerOrders, "Customers")
ordAdapter.Fill(customerOrders, "Orders")
Dim relation As DataRelation = _
customerOrders.Relations.Add("CustOrders", _
customerOrders.Tables("Customers").Columns("CustomerID"), _
customerOrders.Tables("Orders").Columns("CustomerID"))
Dim pRow, cRow As DataRow
For Each pRow In customerOrders.Tables("Customers").Rows
Console.WriteLine(pRow("CustomerID").ToString())
For Each cRow In pRow.GetChildRows(relation)
Console.WriteLine(vbTab & cRow("OrderID").ToString())
Next
Next
As explained here
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.
I'm trying to open an image from my database to a picture box but I just don't how to do it.
I've searched for some answers and I am not familiar with the codes for I am beginner only.
The only codes that I researched about are for connecting the database to the system:
Imports System.Data.OleDb
Module Module1
Public acsconn As New OleDbConnection
Public acsdr As OleDbDataReader
Public acsda As New OleDbDataAdapter
Public acscmd As New OleDbCommand
Public strsql As String
Public acsds As New DataSet
Public Sub connect()
Try
acsconn.ConnectionString = "provider=microsoft.jet.oledb.4.0; data source=|datadirectory|\database1.mdb;"
acsconn.Open()
If acsconn.State = ConnectionState.Open Then
MsgBox("Connected")
Else
MsgBox("Error")
End If
Catch ex As Exception
End Try
End Sub
End Module
I do not know what is next. BTW, those codes - I used it for saving the image to the database.
I think this is the sort of thing you are looking for:
Private Sub HandleRequest(context as HttpContext)
Dim SqlCnn As SqlConnection = Nothing, sql As String
Dim emp_id As Integer
emp_id = Int32.Parse(context.Request.QueryString("id"))
ConnectDB(SqlCnn)
Try
sql = "SELECT image FROM employees (NOLOCK) WHERE ID =" & emp_id
sqlcmd = New SqlCommand(sqlstr, SqlCnn)
Dim imageData As Byte() = DirectCast(sqlcmd.ExecuteScalar(), Byte())
context.Response.ContentType = "image/jpeg"
context.Response.BinaryWrite(imageData)
Catch ex As Exception
ReportError(ex)
Finally
CloseDB(SqlCnn)
End Try
End Sub