Database connection and data saving in SQL Server - database

I have SQL SERVER database file in Project folder. The same file copy in Debug folder. I attach these two files in SQL Server. File in project folder table contains Null value in all field. But there is data in the file attached from the Debug folder. I created the connection string with the file in Project folder. Actually which database file is the correct file? Try to solve this problem.
The Connection String is
Public Conn As SqlConnection
Public Function getConnect() As SqlConnection
Conn = New SqlConnection("Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\EMP_DB.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True")
Return Conn
End Function
And this is my code..
Try
getConnect()
Dim query As SqlCommand
Dim strSQL As String
strSQL = "INSERT INTO EMPLOYEE (EMP_ID,EMP_NAME,EMP_FNAME,EMP_GENDER,EMP_DOB,EMP_CAST,EMP_DEPART,EMP_DESIG,EMP_DOJ,EMP_SALARY,EMP_PF_ESI,EMP_BRANCH,EMP_CONTACT,EMP_ADDRESS)VALUES(#EMP_ID,#EMP_NAME,#EMP_FNAME,#EMP_GENDER,#EMP_DOB,#EMP_CAST,#EMP_DEPART,#EMP_DESIG,#EMP_DOJ,#EMP_SALARY,#EMP_PF_ESI,#EMP_BRANCH,#EMP_CONTACT,#EMP_ADDRESS)"
query = New SqlCommand(strSQL, Conn)
query.Parameters.Add(New SqlParameter("#EMP_ID", TXTEMPID.Text))
query.Parameters.Add(New SqlParameter("#EMP_NAME", TXTNAME.Text))
query.Parameters.Add(New SqlParameter("#EMP_FNAME", TXTFNAME.Text))
query.Parameters.Add(New SqlParameter("#EMP_GENDER", gend))
query.Parameters.Add(New SqlParameter("#EMP_DOB", DTPEMPDOB.Value.Date))
query.Parameters.Add(New SqlParameter("#EMP_CAST", TXTCASTE.Text))
query.Parameters.Add(New SqlParameter("#EMP_DEPART", CMBDEPT.Text))
query.Parameters.Add(New SqlParameter("#EMP_DESIG", CMBDESIG.Text))
query.Parameters.Add(New SqlParameter("#EMP_DOJ", DTPEMPDOJ.Value.Date))
query.Parameters.Add(New SqlParameter("#EMP_SALARY", MTXTSAL.Text))
query.Parameters.Add(New SqlParameter("#EMP_PF_ESI", MTXTPFESI.Text))
query.Parameters.Add(New SqlParameter("#EMP_BRANCH", TXTBRANCH.Text))
query.Parameters.Add(New SqlParameter("#EMP_CONTACT", MTXTCONTACT.Text))
query.Parameters.Add(New SqlParameter("#EMP_ADDRESS", RTXTADDRESS.Text))
Conn.Open()
Dim numAffected = query.ExecuteNonQuery()
'MessageBox.Show(numAffected)
Conn.Close()
If numAffected > 0 Then
Call getConnect()
MessageBox.Show("Successfully Added", "Add", MessageBoxButtons.OK, MessageBoxIcon.Information)
BTNCLEAR.PerformClick()
Else
MsgBox("No record was inserted")
End If
Catch ex As Exception
MsgBox("ERROR: " + ex.Message, MsgBoxStyle.Information, "Add")
End Try
End If
I change my connection string like this...
Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\EMP_DB.mdf;Initial Catalog=EMP_DB;Integrated Security=True;Connect Timeout=30;User Instance=False

User instances are depreciated, and probably what is causing this confusion.
To quote SQL Server MVP Aaron Bertrand:
Using User Instance means that SQL Server is creating a special copy
of that database file for use by your program. If you have two
different programs using that same connection string, they get two
entirely different copies of the database. This leads to a lot of
confusion, as people will test updating data with their program, then
connect to a different copy of their database in Management Studio,
and complain that their update isn't working. This sends them through
a flawed series of wild goose chase steps trying to troubleshoot the
wrong problem.
[Source]
He also goes on to list some alternatives in the same post:
Create or attach your database to a real instance of SQL Server. Your connection string will then just need to specify the instance name, the database name, and credentials. There will be no mixup as Management Studio, Visual Studio and your program(s) will all be connecting to a single copy of the database.
If you're using SQL Server 2012, use SqlLocalDb for local development. See: "Getting Started with SQL Server 2012 Express LocalDB."
Use SQL Server Compact. I like this option the least because the functionality and syntax is not the same - so it's not necessarily going to provide you with all the functionality you're ultimately going to want to deploy.

Related

Changing stored procedure so that it will work with Local connection to SQL Server Db (and update a table)

I have the following code and Insert-statement.. and connection.
SqlConnection con = new SqlConnection();
con.ConnectionString = ("Data Source=DESKTOP-PGHMM6M;Initial Catalog=LocalUsers;Integrated Security=True");
con.Open();
string st = "INSERT INTO data(Username, Password, Hash, EncryptedPassword) VALUES (#Username, #Password, #Hash, #EncryptedPassword)";
SqlCommand cmd = new SqlCommand(st, con);
cmd.Parameters.AddWithValue("#Username", Username);
cmd.Parameters.AddWithValue("#Password", textBox2.Text);
cmd.Parameters.AddWithValue("#Hash", savedPasswordHash);
cmd.Parameters.AddWithValue("#EncryptedPassword", FinalEncryptedPass);
cmd.ExecuteNonQuery(); // invalid object name 'data' < where is this object?
con.Close();
When I run the program it returns the following error:
Invalid object name 'data'
I'm not sure what I did to create this situation. I was fulling around with the "stand-alone sql features" in Visual studio 2017, and I'm not sure where to start, to get back on track to use a local SQL Management Server Studio db that I created.
I found a previous question with the following::
Right click the database project --> Properties
Click Debug
Under Target Connection String, click Edit and select the correct database server
Create a new stored procedure
But I'm not sure what any of this is referring to ^.. any pointers?
welcome to stackoverflow.com
it says you do not have a table (in which you are inserting data) name : "data"...
you must have a database name "LocalUsers". in this database,
create a table name : "data" (with given fields) and you are good to go.

Creating a SQL Server database for the first time at run time

I want to create a SQL Server database at runtime in my vb.net project. I know how to actually code the database but I am wondering where should I actually put the code? Should I be putting the code in the start up form or should it go into a class on it's own? Also, this project will be going on more than one pc at a particular site, so I only want the database to be created the first time the project is activated and then just be able query the database on different pcs after that. How do I do this? All help on this matter would be greatly appreciated.
EDIT:
Ok, so I should have been clearer on this. The project is going to be on 2 different pcs, it is for visitors entering a business. The pcs will be in reception and security. I need both pcs to access the same database with the same details in it. I don't want to have two different databases where details have to be put in twice. For example, if I enter at reception today and then go through security tomorrow, then all I should have to enter in security is why I'm entering the business again, I shouldn't have to put my details in a second time. How do I go about this? As I already said, I know how to code the database, but I want to know how to do what I stated in my question.
Thanks in advance for all help given.
If you add the code in module or in form load then it will execute all the time when the form loads. it is wasting of time to check whether the database exist or not in each run. So it is better to place a button with text "Create database" for this purpose(or menu item). it's click event will load the database. the following code can be used to create the database dynamically on button click
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
'creating and initializing the connection string
Dim myConnectionString As SqlConnection = New SqlConnection("Data Source=(local)\SQLEXPRESS;Initial Catalog=master;Integrated Security=True;Pooling=False")
'since we need to create a new database set the Initial Catalog as Master
'Which means we are creating database under master DB
Dim myCommand As String //to store the sql command to be executed
myCommand = "CREATE database my_db" //the command that creates new database
Dim cmd As SqlCommand = New SqlCommand(myCommand, myConnectionString) // creating command for execution
Try
cmd.Connection.Open() //open a connection with cmd
cmd.ExecuteNonQuery() //Execute the query
cmd.Connection.Close() //Close the connection
Catch
MsgBox(" Already installed database", MsgBoxStyle.Critical, " MaS InfoTech- Warning")
End Try
'Creating table to the dynamicaly created database
Try
Dim cn As SqlConnection = New SqlConnection("Data Source=(local)\SQLEXPRESS;Initial Catalog=my_db;Integrated Security=True;Pooling=False")
'here the connection string is initialized with Initial Catalog as my_db
Dim sql As String //sql query string
sql = "CREATE TABLE customer(cus_name varchar(50) NULL,address varchar(50) NULL,mobno numeric(18, 0) NULL,tin varchar(50) NULL,kg varchar(50) NULL)"
cmd = New SqlCommand(sql, cn) // create command with connection and query string
cmd.Connection.Open()
cmd.ExecuteNonQuery()
cmd.Connection.Close()
Catch
MsgBox(" Already existing table", MsgBoxStyle.Critical, " MaS InfoTech- Warning")
End Try
End Sub

Attached DB is not accessible to make connection

I created a DB using following code.
Dim conn As New SqlConnection("Server=.\SQLExpress;Data Source=;Integrated Security=SSPI")
Dim cmd As New SqlCommand("", conn)
cmd.CommandText = "CREATE DATABASE MyDBTest22 ON ( FILENAME = 'D:\dbTestATTTTTTT.mdf' ), ( FILENAME = 'D:\dbTestATTTTTTT_log.ldf' ) FOR ATTACH"
conn.Open()
cmd.ExecuteNonQuery()
cmd.Dispose()
conn.Dispose()
It ran without any error but when I opened SSMS, I could not see my file attached to the server. Also, I tried to make a connection, but it says file does not exist but when I tried to re-run the above code, it says File already exists.
Something wrong with my way of doing it? I want to see it attached with the instance of my SQL Server Express 2005, using SSMS.
Thanks
You're missing a database to connect to in your connection string - if you want to attach a file, I would recommend connecting to the master database:
Dim conn As New SqlConnection("Server=.\SQLExpress;Database=master;Integrated Security=SSPI")

Using Object to execute SQL statements in Visual Studio

I apologize if my question is simple, but I have done a lot of looking on the Internet and I am having trouble finding a solution.
I have a database connected to Visual Studio where I used the "Connect to Database..." wizard to establish the connection. In the Server Explorer in Visual Studio, I see I have a Data Connection called "newreptDBtest.accdb", and a Server named Mandrew.
Basically I would like to execute SQL statements on this database when clicking a button. So I have a button on a form, and it has the following code:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim sqlconn As New SqlConnection
sqlconn.ConnectionString = "server=Mandrew;Initial Catalog=newreptDBtest.accdb"
Try
sqlconn.Open()
Catch ex As Exception
MessageBox.Show("Error on connection")
End Try
If sqlconn.State = 1 Then
MessageBox.Show("Success!")
End If
End Sub
In General Declarations, I have:
Imports System.Data.SqlClient
Perhaps because it's not a SQL database? I'm not sure. Either way, I have not been able to achieve the "Success!" from the MessageBox. Once I've gotten that, I'm sure I can figure out how to create SQL statements to return certain rows or single pieces of information.
In the newreptDBtest, the table I'd like to be executing queries on is called newrept, and the connection string to the database is:
"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\Andrew\Documents\newreptDBtest.accdb"
tl;dr:
How do I use an object (such as a button) to execute SQL queries on a table inside a database already connected to my project?
Thanks in advance
The classes that you need to use for accessing an MS Access database file are in the System.Data.OleDb namespace. Try this:
Dim ConnString As String = "server=Mandrew;Initial Catalog=newreptDBtest.accdb"
Dim SqlString As String = "put your query here, e.g. Select * From Contacts"
Using conn As New OleDbConnection(ConnString)
Using cmd As New OleDbCommand(SqlString, conn)
cmd.CommandType = CommandType.Text
conn.Open()
Using reader As OleDbDataReader = cmd.ExecuteReader()
While reader.Read()
'access the data using the reader, e.g. reader("ColumnName")
End While
End Using
End Using
End Using
Taken from here
Obviously, you will need to modify it to fit your query but this hightlights the fact that you need to use OleDbConnection to connect to an MS Access file.

How do I connect to SQL Server with VB?

I'm trying to connect to a SQL server from VB. The SQL server is across the network uses my windows login for authentication.
I can access the server using the following python code:
import odbc
conn = odbc.odbc('SignInspection')
c = conn.cursor()
c.execute("SELECT * FROM list_domain")
c.fetchone()
This code works fine, returning the first result of the SELECT. However, I've been trying to use the SqlClient.SqlConnection in VB, and it fails to connect. I've tried several different connection strings but this is the current code:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim conn As New SqlClient.SqlConnection
conn.ConnectionString = "data source=signinspection;initial catalog=signinspection;integrated security=SSPI"
Try
conn.Open()
MessageBox.Show("Sweet Success")
''#Insert some code here, woo
Catch ex As Exception
MessageBox.Show("Failed to connect to data source.")
MessageBox.Show(ex.ToString())
Finally
conn.Close()
End Try
End Sub
It fails miserably, and it gives me an error that says "A network-related or instance-specific error occurred... (provider: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server)
I'm fairly certain it's my connection string, but nothing I've found has given me any solid examples (server=mySQLServer is not a solid example) of what I need to use.
Thanks!
-Wayne
You are using an ODBC DSN as a SqlClient server name. This is not going to work. You have to use a SqlClient connection string, and for SqlClient the DataSource property is the server name or a SQL Native Client server alias (which is not the same as an ODBC DSN).
Replace signinspection with the actual name of your SQL Server host. If is a named instance or listening on a non default port, you have to specify that too, eg: hostname\instancename
Check out connectionstrings.com for samples. It looks like in your python example, you are accessing the DB via ODBC.
The string you are using is connecting with the built in .NET SQL Server DB provider, so you need to use an ODBC connection string OR change your data source to the actual server name (if no other instances) or servername/instance name.
Sure your Server and Database have the same name?
Here you have a link that would allow you to generate a connection string and test it
http://blogs.msdn.com/dhejo_vanissery/archive/2007/09/07/One-minute-Connection-string.aspx.
Well, I went ahead and used an ODBC Connection. It appears that that is what I was wanting in the first place.
In order to do use the ODBC I had to go to http://support.microsoft.com/kb/310985 and install a few files. Following the directions I came up with the following code that seems to work just fine:
Dim conn As OdbcConnection
conn = New OdbcConnection("DSN=SignInspection")
Dim mystring as String = "SELECT * FROM list_domain"
Dim cmd As OdbcCommand = New OdbcCommand(mystring, conn)
Dim reader As OdbcDataReader
Dim columnCount As Integer
Dim output As String
Dim data as Object() = New Object(10) {}
conn.Open()
MsgBox("Connected!")
reader = cmd.ExecuteReader()
While reader.Read()
columnCount = reader.GetValues(data)
output = ""
For i As Integer = 0 To columnCount - 1
output = output & " " & data(i).ToString()
Next
Debug.WriteLine(output)
End While
conn.Close()
Of course I'll have it cleaned up a lot, but I figure maybe someone will end up looking for the same solution, and maybe they'll see my code before they spend too much time.
ed. columsCount -> columCount
You might want to take a look on Microsoft Enterprise Library Data Access Application Block in order to make it easier to connect and to support multiple underlying datastores.
Good success! =)

Resources