I can't seem to insert data to my database - sql-server

I am having issues with my code when I try to insert data into my database, the section where it checks for matching username keeps popping up the error to select another username. I don't know what I am doing wrong, any help will be appreciated.
This is my code:
'Connecting to SQL Database and executing Query
Dim Strconn As String = "Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\phermacy.mdf;Integrated Security=True;User Instance=True"
Dim Strcmd As String = "INSERT INTO tblstaff_info(id,fname,lname,sex,nationality,status,dob,age,nationality,state,address,phone,email,dateemp,username,password) VALUES ('" & txtregid.Text & "','" & txtfname.Text & "','" & txtlname.Text & "','" & cmbstaffsex.Text & "','" & cmbstatus.Text & "','" & dtpickerdob.Text & "','" & txtage.Text & "','" & txtnationality.Text & "','" & txtstateofo.Text & "','" & rtbaddress.Text & "','" & txtphone.Text & "','" & txtemail.Text & "','" & dtpdateemp.Text & "','" & txtusername.Text & "','" & txtpassword.Text & "');"
Dim da As New SqlDataAdapter
Dim ds As New DataSet
Dim sqlcmd As SqlCommand
sqlconn = New SqlConnection(Strconn)
Try
sqlconn.Open()
Catch ex As Exception
MsgBox("Could not connect to DataBase. Application will close now!", vbCritical, "Database Error")
End
End Try
sqlcmd = New SqlCommand(Strcmd, sqlconn)
da.SelectCommand = sqlcmd
sqlcmd.Dispose()
sqlconn.Close()
'Exception Handling-----------------------
Dim exc As Exception = Nothing
Try
da.Fill(ds)
Catch ex As Exception
exc = ex
Finally
If Not (exc) Is Nothing Then
MsgBox("User Name Already Exist. Please select a different User Name!", vbExclamation, "Already Exist")
txtusername.Focus()
Else
MsgBox("Save info Successful.", vbInformation, "Successful")
'Me.Close()
'loginform.Show()
End If
End Try

The whole User Instance and AttachDbFileName= approach is flawed - at best! When running your app in Visual Studio, it will be copying around the .mdf file (from your App_Data directory to the output directory - typically .\bin\debug - where you app runs) and most likely, your INSERT works just fine - but you're just looking at the wrong .mdf file in the end!
If you want to stick with this approach, then try putting a breakpoint on the connection's .Close() call - and then inspect the .mdf file with SQL Server Mgmt Studio Express - I'm almost certain your data is there.
The real solution in my opinion would be to
install SQL Server Express (and you've already done that anyway)
install SQL Server Management Studio Express
create your database in SSMS Express, give it a logical name (e.g. Pharmacy - check your spelling!)
connect to it using its logical database name (given when you create it on the server) - and don't mess around with physical database files and user instances. In that case, your connection string would be something like:
Data Source=.\\SQLEXPRESS;Database=Pharmacy;Integrated Security=True
and everything else is exactly the same as before...
Also see Aaron Bertrand's excellent blog post Bad habits to kick: using AttachDbFileName for more background info.

Related

Connection to a Microsoft SQL Database via VBA (ADODB) with the lowest risk to harm the database

im currently looking for a way to connect to a Microsoft SQL Server Database via VBA (ADODB) with the focus on a minimal risk in harming, block and change the structure of the database. Therefor the access is readonly.
My attemp is the following:
Set DBConn = New ADODB.Connection
Set TmpRecset = New Recordset
DBConn.ConnectionString = pConnStr
DBConn.Open
On Error GoTo TermConnection
With TmpRecset
.ActiveConnection = DBConn
.Source = pQuery
.LockType = adLockReadOnly
.CursorType = adOpenForwardOnly
.CursorLocation = adUseClient
.Open
End With
On Error GoTo TermRecordset
//Doing something useful with TmpRecset
On Error GoTo 0
TermRecordset:
TmpRecset.Close
Set TmpRecset.ActiveConnection = Nothing
TermConnection:
DBConn.Close
Set DBConn = Nothing
End Sub
And I'm using the following connection string:
"Provider=SQLOLEDB;Data Source=IP\Database;Initial Catalog=Databasename;Trusted_connection=yes;"
I used the manual error handling to ensure, that the recordset and the database is closed whatever happens. Via the parameters of the recordset I define the readonly access.
Are there some other mechanisms to make sure, that the integrity of the Database will be ensured?
Best regards
In my opinion there is no reasonable security in Excel. All security should reside on the server. If you want to prevent accidental or malicious changes to the database then the database on the server should be read-only or all users should have read-only access to the SQL server. Furthermore, you can implement traces on the server, SQL audit C2, or make use of extended properties. Yet, all of this is on the side of the SQL server. The things you can do on the "client" side (such as Excel in this case) are only support functions. And so the question is (to me) what kind of support functions can I implement in Excel to ensure SQL server safety. Here are some of the things I do:
(1) Make the connection string dynamic using global variables or storing the string on a hidden sheet. Then you can automatically switch between development server and production server. Example:
Dim conRCServer As ADODB.Connection
Dim rstResult As ADODB.Recordset
Dim strSQL As String
Set conRCServer = New ADODB.Connection
conRCServer.ConnectionString = "PROVIDER=SQLOLEDB; " _
& "DATA SOURCE=" & Ref.Range("C2").Value2 & ";" _
& "INITIAL CATALOG=" & Ref.Range("C4").Value & ";" _
& "Integrated Security=SSPI "
On Error GoTo SQL_ConnectionError
conRCServer.Open
On Error GoTo 0
(2) Have a seperate error handler for connecting to the server and handling SQL syntax errors. Example:
Set rstResult = New ADODB.Recordset
strSQL = "set nocount on; "
strSQL = strSQL & "/* #" & ActiveWorkbook.Path & "/" & ActiveWorkbook.Name & "{" & WorksheetUsers.Name & "}btnDownloadUserDataFromServer */"
strSQL = strSQL & "select v.LastName, "
strSQL = strSQL & " v.FirstName "
strSQL = strSQL & "from vUsers as v "
strSQL = strSQL & "order by v.LastName, v.FirstName "
rstResult.ActiveConnection = conRCServer
On Error GoTo SQL_StatementError
rstResult.Open strSQL
On Error GoTo 0
Here is an error handler for the SQL syntax and in the above example is a seperate handler for the possible SQL connection error.
(3) Incorporate self-identification within the SQL syntax. As you can see in the above example I am also letting the server know which file, which sheet (within the file) and which function within the sheet the user called to execute this statement. If you capture this data on the server with a trace then you can see who is writing their own queries, who is using your standard files and which functions are used (and their respective impact).
(4) If an error occurs you might want to consider writing automated error emails. Example:
SQL_ConnectionError:
Y = MsgBox("Cannot connect to the server. Please make sure that you have a working internet connection. " & _
"Also ensure that are connected to the corporate network and are allowed to access the server. " & _
"Do you want me to prepare an error-email?", 52, "Problems connecting to Server...")
If Y = 6 Then
Set OutApp = CreateObject("Outlook.Application")
Set OutMail = OutApp.CreateItem(0)
With OutMail
.to = Ref.Range("C7").Value2
.CC = Ref.Range("C8").Value2
.Subject = "Problems connecting to database '" & Ref.Range("C4").Value & "' on server '" & Ref.Range("C2").Value & "'"
.HTMLBody = "<span style=""font-size:10px"">---Automatically generated Error-Email---" & _
"</span><br><br>Error report from the file '" & _
"<span style=""color:blue"">" & ActiveWorkbook.Name & _
"</span>' located and saved on '<span style=""color:blue"">" & _
ActiveWorkbook.Path & "</span>'.<br>" & _
"Excel is not able to establish a connection to the server. Technical data to follow." & "<br><br>" & _
"Computer Name: <span style=""color:green;"">" & Environ("COMPUTERNAME") & "</span><br>" & _
"Logged in as: <span style=""color:green;"">" & Environ("USERDOMAIN") & "/" & Environ("USERNAME") & "</span><br>" & _
"Domain Server: <span style=""color:green;"">" & Environ("LOGONSERVER") & "</span><br>" & _
"User DNS Domain: <span style=""color:green;"">" & Environ("USERDNSDOMAIN") & "</span><br>" & _
"Operating System: <span style=""color:green;"">" & Environ("OS") & "</span><br>" & _
"Excel Version: <span style=""color:green;"">" & Application.Version & "</span><br>" & _
"<br><span style=""font-size:10px""><br>" & _
"Possible reasons for this error include: (1) no Internet connection, (2) no working VPN connection to the corporate network, " & _
"(3) the server is currently offline, (4) DNS authentication problems, (5) ... other reasons ..., " & _
"(6) the user does not have the required permission to connect to the underlying database on the server." & _
"<br><br>---Automatically generated Error-Email---"
.Display
End With
Set OutMail = Nothing
Set OutApp = Nothing
End If
Exit Sub
I also looked into your approach of changing the connection parameters. But in most corporate environments I have worked for these connection parameters have been overridden (for example ADODB.Connection.CommandTimeout is overridden by the server's SQL timeout per user or Windows corporate presets if they exist). So, they did not work for me. But the above worked rather well for me and the companies I worked for over the last couple of years.
Let me know if this is the kind of answer you've been looking for.

INSERT permission was denied on the object 'employee_info', database 'payroll' schema dbo

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim myconnection As SqlConnection
Dim mycommand As SqlCommand
Dim ra As Integer
myconnection = New SqlConnection("server=IAI-004;uid=;pwd=;database=payroll")
myconnection.Open()
mycommand = New SqlCommand("INSERT INTO employee_info([employee_id],[first_name],[last_name],[middle_name],[email],[telephone],[gender],[status],[date_birth],[hire_date]) values ('" & Employee_idTextBox.Text & "','" & First_nameTextBox.Text & "','" & Last_nameTextBox.Text & "','" & Middle_nameTextBox.Text & "','" & EmailTextBox.Text & "','" & TelephoneTextBox.Text & "','" & GenderTextBox.Text & "','" & StatusTextBox.Text & "','" & Date_birthDateTimePicker.Text & "','" & Hire_dateDateTimePicker.Text & "')", myconnection)
mycommand.ExecuteNonQuery()
MessageBox.Show("New Row Inserted" & ra)
myconnection.Close()
End Sub
INSERT permission was denied on the object 'employee_info', database 'payroll' schema dbo
how can i resolve this problem?
You'll need to do this (presumably) in SQL-Server (SSMS).
Right-click the table in SQL-Server and give INSERT permissions to the user.
(...)
Right Click the table
Properties
Permissions
(if necessary) add the user or role
click on the user/role
permission insert, put a check-mark in the 'grant' box.
BTW -- you can do this via TSQL directly, but if you're having this problem now (you mention that you're new), then maybe start with the GUI, per above first.
Also -- this assumes you have access to do this in SSMS. If you're not the DBA / DBO, then you might need to contact somebody... :-)
Right Click on the Application Pool concerned.
Click Advanced Settings
Indentify Identity,
Select LocalSystem
That should do the job.
If Answer provided previously works, then it means everytime the password changes, which must change in a normal Enterprise, you will need to update these connection strings as well, and you dont want to do that.
you can resolve this problem with re-run your last add-migration :
for example my last migration name is : initial
1: Add-Migration "initial" -force
2: Update-Database
Run python as an admin then execute the code. That solved the problem for me.

VB to SQL server

I'm trying to insert new data into an SQL server from what user had input in a textbox.
My code is not functioning, please help me.
Dim con As New SqlConnection
Dim cmd As New SqlCommand
con.ConnectionString = "Data Source=LANDSLIDE\SQLSERVER2005;Initial Catalog=PayrollSQL;User ID=sa;Password=lismyadmin"
cmd.Connection = con
con.Open()
cmd.CommandText = "INSERT INTO dbo.Member ([Name], [Code], [NRIC]) VALUES(" & TextBox1.Text & "," & TextBox2.Text & "," & TextBox3.Text & ")"
cmd.ExecuteNonQuery()
con.Close()
You ought to use parameterised queries. Something like:
cmd.CommandText = "INSERT INTO dbo.Member ([Name], [Code], [NRIC]) VALUES(#Name,#Code,#NRIC)"
cmd.Parameters.AddWithValue("#Name",TextBox1.Text)
cmd.Parameters.AddWithValue("#Code",TextBox2.Text)
cmd.Parameters.AddWithValue("#NRIC",TextBox3.Text)
At the moment, you're ending up with your strings appearing literally in your SQL statement - and whatever values you're retrieving from TextBox1-3 aren't valid pieces of SQL (hopefully - if they are actually valid SQL, you're performing SQL injection)
(By the way, you're allowed to rename controls - you ought to rename those TextBoxes so that you don't have to remember that, say, TextBox2 is the one for code)
May be it will work or else provide error message:
cmd.CommandText = "INSERT INTO dbo.Member ([Name], [Code], [NRIC]) VALUES('" & TextBox1.Text & "','" & TextBox2.Text & "','" & TextBox3.Text & "')"

'800a0e78' - object closed - worked previously

I've searched high and low to resolve this one, but can't seem to fix it on my own. I'm new to classic ASP but a very long time PhP dev.
I'm getting
ADODB.Recordset error '800a0e78'
Operation is not allowed when the object is closed.
/sdd/fx_mlogin.asp, line 54
While logging in to the site i'm working on. The line's that's its referencing is:
Set rs = cmd.Execute
If RS.BOF or RS.EOF then
More relevant code:
Set cn = Server.CreateObject("ADODB.Connection")
cn.Open MM_ap_connect_STRING
Set cmd = Server.CreateObject("ADODB.Command")
Set cmd.ActiveConnection = cn
cmd.CommandText = "sd_member_login " & "'" & guid & "', " & """" & trim(user) & """, " & "'" & trim(pw) & "', " & "'" & uip & "', " & "'" & uagent & "', " & "'" & logintrack & "'"
Set rs = cmd.Execute
If rs.BOF or rs.EOF then
The kicker is that the site worked before and we're moving hosts. The connection is apparently working, but I'm suspicious that its still the issue. My connection string is
MM_ap_connect_STRING = "Provider=SQLOLEDB;Data source=sql2103.shared-servers.com,1087;Initial catalog=database;User Id=username;Password=password;"
But obviously with the username, password, and database fields filled in. I'm also connecting to a SQL 2005 database. Any help would be appreciated! Let me know if I need to provide any more information.
Try adding the T-SQL line:
SET NOCOUNT ON
to the top of the SQL being executed.
I had this exact issue. For me the answer was my stored procedure had an owner of DBO. Which my user for the previous database was set to DBO. On our destination database there was a different DBO, which caused a execute permissions issue. Just changed my db user to DBO and it's working now. Hope that helps.

How to update MS Access Database (vb.net)

I am created a journal program for an internship project and I am using a MS-Access Database. I am programming in VB.net. Now, I am trying to make it so that they can "Update" their journals, meaning that they click on their calendar date and it brings them to that journal if they have one for that date. If they have one for that date then it shows the title and journal text entry for that date. I want to make it so that any changes they have made to the journal (editing the textbox fields) are also changed in the database when they click the update button. Here's what i have so far
Private Sub COE_JournalBtn_Click(sender As System.Object, e As System.EventArgs) Handles COE_JournalBtn.Click
If DateTimePicker1.Value <> Nothing Then
If TitleTxt.Text <> "" Then
If JournalTextRtxt.Text <> "" Then
myConnection.Open()
Dim DatePicked As String = DateTimePicker1.Value
Dim cmd As OleDbCommand
Dim str As String
Try
MyJournalTitle = TitleTxt.Text
MyJournalText = JournalTextRtxt.Text
str = "UPDATE Journals SET JournalTitle='" & MyJournalTitle & "', JournalText='" & MyJournalText & "' WHERE JournalDate=" & DatePicked
cmd = New OleDbCommand(str, myConnection)
cmd.ExecuteNonQuery()
myConnection.Close()
Catch ex As Exception
MessageBox.Show("There was an error processing your request. Please try again." & vbCrLf & vbCrLf & _
"Original Error:" & vbCrLf & vbCrLf & ex.ToString, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
myConnection.Close()
End Try
myConnection.Close()
End If
End If
End If
End Sub
Now my update string by itself is
"UPDATE Journals SET JournalTitle='" & MyJournalTitle & "', JournalText='" & MyJournalText & "' WHERE JournalDate=" & DatePicked
Now, what happens, is absolutely nothing. No errorboxes come up. No messageboxes appear. The program doesn't freeze. And the database remains unchanged. What am I doing wrong? Is there an error in my code or something missing? Please help me because I really want to figure this out and i've been looking everywhere for a solution in VB.net and cannot find one that applies to me being that I am using MS-Access and NOT SQL.
Thanks in advance,
Richard Paulicelli
Use a parametrized query to avoid Sql Injection Attacks and quoting problems
str = "Journals SET JournalTitle=?, JournalText=? WHERE JournalDate=?"
cmd = New OleDbCommand(str, myConnection)
cmd.Parameters.AddWithValue("#jounalTitle", MyJournalTitle )
cmd.Parameters.AddWithValue("#journalText", MyJournalText)
cmd.Parameters.AddWithValue("#journalDate", DatePicked)
cmd.ExecuteNonQuery()
Using parameters will free your code from that continue quoting that expose your code to an high chance of typing errors. And you don't have any problem with Sql Injection
You may have a problem with this part of your UPDATE statement:
"' WHERE JournalDate=" & DatePicked
If the Journals field, JournalDate, is Date/Time data type, surround the date string value with Access date delimiter characters (#).
"' WHERE JournalDate=#" & DatePicked & "#"
You can also convert your date string to yyyy-mm-dd format to avoid misinterpreting the date literal based on local.
I agree with the suggestions to use a parameter query for this instead. I'm just trying to help you understand why the original attempt may have failed.

Resources