I am trying to save data to an mdf file which has been detached from SQL server and added to my APP_DATA folder in Solution Explorer, but I am unable do that. Your help will be appreciated. Thank you! Here is my code:
Dim con As New SqlConnection
Dim cmd As New SqlCommand
Dim EmployeeNo As Integer
Dim EmployeeName As String
Dim SupervisorName As String
Dim DateCreated As Date
Dim WeekRange As String
Dim MonthRange As String
Dim ScheduleIn As String
Dim ScheduleOut As String
Dim WorkStatus As String
EmployeeNo = EmpNoText.Text
EmployeeName = EmpNameText.Text
SupervisorName = TeamLeadDropDown.Text
DateCreated = DateCreatedTextBox.Text
WeekRange = WeekRangeTextBox.Text
MonthRange = MonthDropDown.Text
ScheduleIn = ScheduleInBox.Text
ScheduleOut = ScheduleOutBox.Text
WorkStatus = StatusDropDown.Text
Try
con.ConnectionString = "Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\Program Files\Microsoft SQL Server\MSSQL10_50.SQLEXPRESS\MSSQL\DATA\JIBKPI.mdf;Initial Catalog=JIBKPI;Integrated Security=True"
con.Open()
cmd.Connection = con
cmd.CommandText = "INSERT INTO AgentAttendance ([EmployeeNo], [EmployeeName], [SupervisorName], [DateCreated], [WeekRange], [MonthRange], [ScheduleIn], [ScheduleOut], [WorkStatus]) VALUES (#EmployeeNo, #EmployeeName, #SupervisorName, #DateCreated, #WeekRange, #MonthRange, #ScheduleIn, #ScheduleOut, #WorkStatus,)"
cmd.ExecuteNonQuery()
MsgBox("Successfuly saved!", MsgBoxStyle.Information + MsgBoxStyle.OkOnly)
Catch ex As Exception
MsgBox("Error: Unable to save data.")
Finally
con.Close()
End Try
In my web.config the connection string is:
<connectionStrings>
<add name="JIBKPIConnectionString" connectionString="Data Source=(LocalDB)\v11.0;AttachDbFilename="C:\Program Files\Microsoft SQL Server\MSSQL10_50.SQLEXPRESS\MSSQL\DATA\JIBKPI.mdf";Initial Catalog=JIBKPI;Integrated Security=True" providerName="System.Data.SqlClient"/>
Looking at your code, first thing I notice is that you're using parameters in your query:
cmd.CommandText = "INSERT INTO AgentAttendance ([EmployeeNo], [EmployeeName], [SupervisorName], [DateCreated], [WeekRange], [MonthRange], [ScheduleIn], [ScheduleOut], [WorkStatus]) VALUES (#EmployeeNo, #EmployeeName, #SupervisorName, #DateCreated, #WeekRange, #MonthRange, #ScheduleIn, #ScheduleOut, #WorkStatus,)"
But nowhere have you actually set those parameters. So before you execute your query you need to create those parameters. Something like:
cmd.Parameters.Add("#EmployeeNo", SqlDbType.Int)
command.Parameters("#EmployeeNo").Value = EmployeeNo
etc...
Then execute your query:
cmd.ExecuteNonQuery()
Also, if you're going to use the connection string in your web.config, remove both the " from the AttachDbFilename
Change this:
AttachDbFilename="C:\Program Files\Microsoft SQL Server\MSSQL10_50.SQLEXPRESS\MSSQL\DATA\JIBKPI.mdf"
to this:
AttachDbFilename=C:\Program Files\Microsoft SQL Server\MSSQL10_50.SQLEXPRESS\MSSQL\DATA\JIBKPI.mdf
EDIT: remove the last comma from your query after #WorkStatus
#WorkStatus,)"
becomes
#WorkStatus)"
Related
This is a very simple task of adding a record to a SQL table using vb.net, but I am struggling.
Dim query As String = String.Empty
query &= "INSERT INTO StudentInfo(StudentName,StudentPhone) VALUES(#param1,#param2)"
Using conn As New SqlConnection("csStudentDB")
Using comm As New SqlCommand()
With comm
.Connection = conn
.CommandType = CommandType.Text
.CommandText = query
.Parameters.AddWithValue("#StudentName", txtStudentName.Text)
.Parameters.AddWithValue("#StudentPhone", txtStudentPhone.Text)
End With
Try
conn.Open()
comm.ExecuteNonQuery()
Catch ex As Exception
End Try
End Using
End Using
Web.config:
<connectionStrings>
<add name="csStudentDB" connectionString="Data Source=xxxxx;Initial Catalog=xxxxx;Integrated Security=True"
providerName="System.Data.SqlClient" />
</connectionStrings>
I want to add a record to my table, but I get an error at the error is occuring at Using conn As New SqlConnection(....."
"Format of the initialization string does not conform to specification
starting at index 0."
Any solutions will be appreciated.
if all else fails, try this:
Using conn As New SqlConnection("Data Source=YourDBServerName;Initial Catalog=YourDBName;Integrated Security=True")
Using comm As New SqlCommand()
With comm
.Connection = conn
.CommandType = CommandType.Text
.CommandText = query
.Parameters.AddWithValue("#StudentName", txtStudentName.Text)
.Parameters.AddWithValue("#StudentPhone", txtStudentPhone.Text)
End With
Try
conn.Open()
comm.ExecuteNonQuery()
Catch ex As Exception
End Try
End Using
End Using
In your INSERT statement you are using parameters #param1 and #param2. But in your code you are using #StudentName and #StudentPhone. They need to be the same.
Also, I have added the bit to retrieve the connection string.
For example:
Dim connString As String = String.Empty
connString = System.Configuration.ConfigurationManager
.ConnectionStrings("csStudentDB").ConnectionString
Dim query As String = String.Empty
query = "INSERT INTO StudentInfo(StudentName,StudentPhone) VALUES(#StudentName,#StudentPhone)"
Using conn As New SqlConnection(connString)
Using comm As New SqlCommand()
With comm
.Connection = conn
.CommandType = CommandType.Text
.CommandText = query
.Parameters.AddWithValue("#StudentName", txtStudentName.Text)
.Parameters.AddWithValue("#StudentPhone", txtStudentPhone.Text)
End With
Try
conn.Open()
comm.ExecuteNonQuery()
Catch ex As Exception
End Try
End Using
End Using
try this:
With comm
.Connection = conn
.CommandType = CommandType.Text
.CommandText = query
.Parameters.AddWithValue("#param1", txtStudentName.Text)
.Parameters.AddWithValue("#param2", txtStudentPhone.Text)
End With
since in your query
query &= "INSERT INTO StudentInfo(StudentName,StudentPhone) VALUES(#param1,#param2)"
you are specify the parameters as #param1 and #param2 so you must use the samme in .Parameters.AddWithValue
I am trying to connect to an Oracle database using asp.net.
I have tns.ora entries set up correctly (I believe) in web.config file as shown below:
<add name="constr" connectionString="Data Source=(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=myhostname)(PORT=1521))(CONNECT_DATA=(SERVICE_NAME=myServiceName)));User Id=myUsername;Password=myPassword;"/>
Then I use the connection string in codebehind:
Dim strConnString As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
I declared Oracle Connection:
Imports System.Data.OracleClient
First, I am getting an error that
Namespace or Type declared in Imports System.Data.OracleClient
doesn't contain any public member or is not found
When I removed it, I got the following error:
A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible...
I think that this has to do with Imports statement.
Any ideas how to fix this error?
Private Sub PopulateContinents()
Dim oOracleConn As OracleConnection = New OracleConnection()
Dim strConnString As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
Dim strQuery As String = "select deptID, DeptName from Dept"
Dim con As OracleConnection = New SqlConnection(strConnString)
Dim cmd As OracleCommand = New SqlCommand
cmd.CommandType = CommandType.Text
cmd.CommandText = strQuery
cmd.Connection = con
oOracleConn.Open()
ddlContinents.DataSource = cmd.ExecuteReader
ddlContinents.DataTextField = "deptID"
ddlContinents.DataValueField = "DeptName"
ddlContinents.DataBind()
con.Close()
End Sub
Its seems that the application is not getting the correct connection string.
First, try to clear all connection strings in web.config:
<connectionStrings>
<clear />
<add name="...
Second, try to specify the provider you want to use:
<add name="your.cs.name"
providerName="Oracle.DataAccess.Client"
connectionString="Data Source=//server:1521/instancename;User ID=UID;Password=PASS" />
I would like to fire an SQL Query from my ASP.NET page (vb), what the query will do is to look for the maximum value from a column and then return that value and place it into a label in the webpage.
Currently i dont know to fire the SQL command and then return with the value, a correction to my code is hihgly appreciated.
Dim Con As New SqlConnection
Dim SQL As String
Con.ConnectionString = "Data Source=WCRDUSMJEMPR9\SQLEXPRESS;Initial Catalog=MicroDB;Integrated Security=True"
Con.Open()
SQL = "SELECT MAX(ID_ControlCharts) FROM ControlCharts"
Label123.Text = SQL
The code above is not working, i know that i need to execute the query however i'm totally lost.
You need to create sql command and call executescalar method.
Ex:
Dim Con As New SqlConnection
Dim SQL As String
Con.ConnectionString = "Data Source=WCRDUSMJEMPR9\SQLEXPRESS;Initial
Catalog=MicroDB;Integrated Security=True"
Con.Open()
Dim cmd as new SQLCommand(sql,Con)
Dim obj = cmd.ExecuteScalar()
if(obj!=null)
Label123.Text = obj.ToString()
end if
Con.Close()
Dim com as SqlCommand = Con.CreateCommand
Label123.Text = com.ExecuteScalar(SQL)
I have following code to fill my dataset (ASP.Net).
Dim conStr As String = "Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\dbTest.mdf;Integrated Security=True;User Instance=True"
Dim sqlQry As String = "SELECT * FROM tblTest"
Dim dAdt As New SqlDataAdapter(sqlQry, conStr)
Dim dSet As New DataSet()
dAdt.Fill(dSet, "tblTest")
Then I am using following to edit my record
Dim dRow As DataRow
dRow = dSet.Tables("tblTest").Rows(1)
dRow.BeginEdit()
dRow.Item("Name") = txtName.Text
dRow.EndEdit()
dSet.Tables("tblTest").AcceptChanges()
it does not generate any error but does not edit the record too. Same is happening when I try to delete record using delete command. Please advise.
Thanks
I think you need to call "update" before AcceptChanges.
Something like:
dset.Update();
Try adding the BeginEdit() and AcceptChanges() methods, like this:
drRow.BeginEdit()
drRow("Name") = txtName.Text
dsSet.Tables("tblTest").AcceptChanges()
I have this mySQL code that connects to my server. It connects just fine:
Dim MyConString As String = "DRIVER={MySQL ODBC 3.51 Driver};" & _
"SERVER=example.com;" & _
"DATABASE=xxx;" & _
"UID=xxx;" & _
"PASSWORD=xxx;" & _
"OPTION=3;"
Dim conn As OdbcConnection = New OdbcConnection(MyConString)
conn.Open()
Dim MyCommand As New OdbcCommand
MyCommand.Connection = conn
MyCommand.CommandText = "select * from userinfo WHERE emailAddress = '" & theUN & "'""
MyCommand.ExecuteNonQuery()
conn.Close()
However, i have an old Classic ASP page that uses "oRecordset" to get the data from the mySQL server:
Set oConnection = Server.CreateObject("ADODB.Connection")
Set oRecordset = Server.CreateObject("ADODB.Recordset")
oConnection.Open "DRIVER={MySQL ODBC 3.51 Driver}; SERVER=example.com; PORT=3306; DATABASE=xxx; USER=xxx; PASSWORD=xxx; OPTION=3;"
sqltemp = "select * from userinfo WHERE emailAddress = '" & theUN & "'"
oRecordset.Open sqltemp, oConnection,3,3
And i can use oRecordset as follows:
if oRecordset.EOF then....
or
strValue = oRecordset("Table_Name").value
or
oRecordset("Table_Name").value = "New Value"
oRecordset.update
etc...
However, for the life of me, i can not find any .net code that is similar to that of my Classic ASP page!!!!!
Any help would be great! :o)
David
This is what you have to do:
instead of MyCommand.ExecuteNonQuery you should use MyCommand.ExecuteQuery and assign it to DataReader.
Check out this sample:
Dim myConnection As SqlConnection
Dim myCommand As SqlCommand
Dim dr As New SqlDataReader()
'declaring the objects
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs)_
Handles MyBase.Load
myConnection = New SqlConnection("server=localhost;uid=sa;pwd=;database=pubs")
'establishing connection. you need to provide password for sql server
Try
myConnection.Open()
'opening the connection
myCommand = New SqlCommand("Select * from discounts", myConnection)
'executing the command and assigning it to connection
dr = myCommand.ExecuteReader()
While dr.Read()
'reading from the datareader
MessageBox.Show("discounttype" & dr(0).ToString())
MessageBox.Show("stor_id" & dr(1).ToString())
MessageBox.Show("lowqty" & dr(2).ToString())
MessageBox.Show("highqty" & dr(3).ToString())
MessageBox.Show("discount" & dr(4).ToString())
'displaying the data from the table
End While
dr.Close()
myConnection.Close()
Catch e As Exception
End Try
HTH
Dim conn As OdbcConnection = New OdbcConnection("DRIVER={MySQL ODBC 3.51 Driver}; SERVER=xxx.com; DATABASE=xxx; UID=xxx; PASSWORD=xxx; OPTION=3;")
conn.Open()
Dim MyCommand As New OdbcCommand
MyCommand.Connection = conn
MyCommand.CommandText = "SELECT * FROM userinfo"
Dim rst = MyCommand.ExecuteReader()
While rst.Read()
response.write(rst("userID").ToString())
End While
conn.Close()
Dim email As String = "anyone#anywhere.com"
Dim stringValue As String
Using conn As OdbcConnection = New OdbcConnection(MyConString)
conn.Open()
Dim sql = "Select ... From userInfo Where emailAddress = #Email"
Using cmd As OdbcCommand = New OdbcCommand(sql, conn)
cmd.Parameters.AddWithValue("#Email", email)
Dim reader As OdbcDataReader = cmd.ExecuteReader()
While reader.Read()
stringValue = reader.GetString(0)
End While
End Using
conn.Close()
End Using
'To do an Update
Using conn As OdbcConnection = New OdbcConnection(MyConString)
conn.Open()
Dim sql As String = "Update userInfo Set Column = #Value Where PK = #PK"
Using cmd As OdbcCommand = New OdbcCommand(sql, conn)
cmd.Parameters.AddWithValue("#Email", email)
cmd.ExecuteNonQuery()
End Using
End Using
'To do an Insert
Using conn As OdbcConnection = New OdbcConnection(MyConString)
conn.Open()
Dim sql As String = "Insert userInfo(Col1,Col2,...) Values(#Value1,#Value2...)"
Using cmd As OdbcCommand = New OdbcCommand(sql, conn)
cmd.Parameters.AddWithValue("#Col1", value1)
cmd.Parameters.AddWithValue("#Col2", value2)
...
cmd.ExecuteNonQuery()
End Using
End Using
First, even in ASP Classic, it is an absolutely horrid approach to concatenate a value directly into a SQL statement. This is how SQL Injection vulnerabilities happen. You should always sanitize values that get concatenated into SQL statements. In .NET, you can use parametrized queries where you replace the values that go into your query with a variable that begins with an # sign. You then add a parameter to the command object and set your value that way. The Command object will sanitize the value for you.
ADDITION
You mentioned in a comment that your ASP Classic code is shorter. In fact, the .NET code is shorter because there are a host of things happening that you do not see and have not implemented in your ASP Classic code. I already mentioned one which is sanitizing the inputs. Another is logging. Out of the box, if an exception is thrown, it will log it in the Event Log with a call stack. To even get a call stack in ASP Classic is a chore much less any sort of decent logging. You would need to set On Error Resume Next and check for err.number <> 0 after each line. In addition, without On Error Resume Next, if an error is thrown, you have no guarantee that the connection will be closed. It should be closed, but the only way to know for sure is to use On Error Resume Next and try to close it.
Generally, I encapsulate all of my data access code into a set of methods so that I can simply pass the SQL statement and the parameter values and ensure that it is called properly each time. (This holds true for ASP Classic too).