Connect SQL Express 2012 vb.net - sql

I have been working on this for a few days now. I am trying to make vb.net forms app for my database. Right now I am working on a login form and a main form. I have researched many different websites and played with this string forever, but i can not get a connection to my db. I get different errors saying the machine refused it, then ill get a timeout error, then it will go back to refusal.
Dim conn As New MySqlConnection
If conn.State = ConnectionState.Closed Then
conn.ConnectionString = ("Server=192.168.0.2;Database=Sunshinetix;User=sa;Password=sunshine;")
End If
Can someone please tell me what I am doing wrong? I am a beginner in vb.net. And this is a remote server, but LAN.
Thanks!
PS: Is is because I am using SQL Express?
Enable remote connections for SQL Server Express 2012
I've had that article open for a few days and it has helped me a lot to this point.

If you are using Sql Server express, you need to use a SqlConnection, not a MySqlConnection. That one is for use with MySQL, which is a different implementation of SQL than Microsoft SQL Server
Of course, Microsoft also offers the OleDbConnection as kind of a "catch-all" (see more here: Difference between Sql Connection and OLEDB Connection). Still, if I know I'm going to stick with a particular SQL provider, then I generally use the specialized version.
Also, if you're ever interested, here is a small list of common SQL providers:
Microsoft SQL Server - proprietary SQL provider developed and supported by Microsoft
MySQL - Free, open source relational database system developed by Oracle. Very popular with web developers.
PostgreSQL - another open-source RDBMS. Gaining popularity due to its flexibility and adherence to standards.
SQLite - a small, SQL provider with an emphasis on portability. Unlike the others, it uses local database files rather than a remote server. This has made it pretty much the default choice when developing mobile applications that require local storage.

Try this:
Dim SQLConn As SqlConnection = New SqlConnection
SQLConn.ConnectionString = "Data Source=servername;" & _
"Initial Catalog=databasename;" & _
"User ID=username;" & _
"Password=userpassword;"
The reason why you can't connect is that you are using MySQLConnection that is connectiong to connecting to MySQL DB which is different from MS SQL so you need to use SqlConnection
You might also check this:
http://support.microsoft.com/kb/308656
Also check this site:
http://www.connectionstrings.com/sql-server/
To know preferences of your SqlConnection string according to SQL version.
Try this to test your connection string:
Dim connectString as String = ""
Try
Dim objConn As SqlConnection = New SqlConnection(Server=192.168.0.2;Database=Sunshinetix;User=sa;Password=sunshine;)
objConn.Open()
objConn.Close()
Msgbox("Successfully connected to database!")
Catch ex As Exception
Msgbox("Cannot connect, Error:" & ex.Message)
End Try

Related

Connect Microsoft Access to phppgadmin to query in PostgreSQL

My goal is to import data into Microsoft Access to create a database which I can reference from an excel dashboard for analysis.
I can't find any information on how to connect access to allow me to query the database on phpPgAdmin.
Any advice, direction or solution is highly appreciated.
Please let me know if there more details are necessary.
MS Access is a multifaceted thing as many tend to conflate and confuse its frontend GUI .exe application and the distinct backend database (JET/ACE SQL engine which are Windows .dll files). Most of the time we refer to its MS Office app. Technically, MS Access is really the same type of product as phppgadmin: a GUI console to a database, only its default database is the aforementioned engine but can also integrate other ODBC/OLEDB-connected backends including Postgres, Oracle, MySQL, SQL Server, etc.
Through various means, you can integrate MS Access as a medium between PostgreSQL and Excel without any single migration (export/import) of data.
Linked Tables - Directly connect to Postgres tables using its ODBC Driver.
Pass-through queries - Create saved queries using Postgres dialect within MS Access.
ADO Connections (see Importing data programmatically and by using functions) - Bypass MS Access and have Excel connect directly to Postgres also using OLEDB provider or ODBC driver. Below is the programmatic version showing two connection string examples, but you can save connection objects via the Excel ribbon UI.
Dim strConnection
' REFERENCE Microsoft ActiveX Data Objects, #.# Library
Dim conn As ADODB.Connection, rst As ADODB.Recordset
' ODBC AND OLEDB CONNECTIONS (SELECT ONE)
strConnection = "Driver={PostgreSQL};Server=IPaddress;Port=5432;" _
& "Database=myDataBase;Uid=myUsername;Pwd=myPassword;"
strConnection = "Provider=PostgreSQL OLE DB Provider;Data Source=myServerAddress;" _
& "location=myDataBase;User ID=myUsername;password=myPassword;"
conn.Open strConnection
rst.Open "SELECT * FROM myPGTable", conn
By the way, above is the VBA version to be run in an Excel macro but ADO is a COM object and hence can be integrated in COM-interfaced languages including PHP, Python, R, Java, etc.

Multiple readers access database

I've read about an option in the connection string called MARS (MultipleActiveResultSets), but from what I've gathered it is only a valid argument for Sql Server 2005. Is there an equivalent setting for OleDB to open an access database with multiple readers?
I am aware that I can create multiple connections, one for each reader. I am currently doing this, but it would preferable to execute both readers on a single connection. Here's my current connection string:
"Provider=Microsoft.Jet.Oledb.4.0;Data Source=C:\MyDb.mdb;Jet OLEDB:Database Password=MyPassword"

How do I refer to SQL Server database with SqlDataAdapter

I'm new to C# and I'm learning it by following a tutorial.
I've created a SQL Server database (Database1.sdf) with one table and few columns by clicking "Add New Item" on my project.
SqlConnection conn = new SqlConnection("Data Source=.\\SQLEXPRESS;AttachDbFilename=??????;Integrated Security=True;Connect Timeout=30;User Instance=True");
DataTable dt = new DataTable();
SqlDataAdapter SDA = new SqlDataAdapter("SELECT * FROM Database1 WHERE Titel like " + int.Parse(textBox1.Text), conn);
SDA.Fill(dt);
dataGridView1.DataSource = dt;
As you see the "???" part is where I'm stuck. I tried using the path of the database
C:\Users\1\Documents\Visual Studio 2010\Projects\Opdracht0\Opdracht0\Database1.sdf
But that is not working. When I run it, I get:
Input string was not in a correct format.
and this line is red:
SqlDataAdapter SDA = new SqlDataAdapter("SELECT * FROM Database1 WHERE Titel like" + int.Parse(textBox1.Text), conn);
As you can see it's a simple SQL statement but even that won't work.
Any tips are appreciated!
Your main problem is you're mixing two incompatible types of databases:
your database1.sdf file is a SQL Server Compact Edition database file
your SqlConnection and SqlCommand however are used for full-fledged SQL Server (Express) versions - and those are NOT compatible with SQL Server Compact!
So either you need to
keep using your SQL Server Compact database (database1.sdf) - but in that case, you need to use SqlCeConnection and SqlCeCommand and those commands
OR THEN:
you switch to a real SQL Server (Express, Standard, Enterprise) and in that case you can use SqlConnection and SqlCommand
To connect to MS SQL Server database from C#.NET, you need to create a connection string such as below:
private SqlConnection connection;
private string connectionString =
#"Server=(local);Database=Embedding_SQL_Test;User ID=sa;Password=123";
connection = new SqlConnection( connectionString );
Next, you use the SqlConnection object created above to create a 'SqlCommand', as shown below:
SqlCommand cmd = new SqlCommand( "select * from Customer where CustomerID = #Cid", connection);
The SQL query shown here can be replaced by a SELECT, INSERT, UPDATE queries etc.
Next to execute the SQL queries in the database, you use the following methods:
ExecuteReader - to execute SELECT queries
ExecuteNonQuery - to execute INSERT, DELETE, UPDATE, and SET statements.
This is a very short description of how to connect to SQL Server database from C# and execute SQL queries in the database.
For details about the connection string, the methods and their parameters check the following link: ( http://www.shahriarnk.com/embedding-sql-c-sharp-java-shahriar/ )
Here you will also find details about how to pass parameters to the SQL queries as well as calling stored procedures and much more.
Here's how I would go about it. I would go to MSDN and type SqlConnection into the search box. After poking around a bit (because they've deep-sixed my favorite connection string examples), I'd find something like this which has some examples like:
Persist Security Info=False;Integrated Security=true;Initial Catalog=Northwind;server=(local)
Data Source=MSSQL1;Initial Catalog=AdventureWorks;Integrated Security=true;
Usually, the server name is the same as the Computer's name, though SQL Express may do this differently. Or, (local) may work here. These connection strings will log into SQL Server with the user's Windows credentials. For a web application the actual user may depend on whether impersonation is used, etc. (And, yes, the connection string should go into the web.config so it can be updated without recompiling the app. If this is a web app.)
At any rate, if this doesn't work for you, you can use the same search strategy to find other connection string examples on MSDN or Google.

Is it possible to have a SQL database with Excel files as "data source"?

Is it possible to make some kind of link from SQL to Excel making the Excel documents the true datasource? I don't want any data to be stored in SQL, all data editing will be done in the Excel sheets.
I know this is far from optimal but I don't have a choice, the data needs to stay in Excel.
I know there is an option to do this kind of links in Access and there I can access the data from within VS but I would really prefer SQL.
It's also possible to use the Jet driver directly from your application and skip out SQL server.
I know this isn't a proper answer to your question but another thought that may be useful :)
Yes, you can set up excel as a linked server. You'll need to use a jet driver but this is only available on 32bit machines (Microsoft dropped their support a while back). In other words, this is completely not scale-able and not recommended in most production environments.
If you want to choose Excel as a datasource then you can connect to it using .Net Oledb provider.
Consider VB.Net example below to read rows on excel sheet:
imports System.Data.OleDb
dim connstr as string = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=d:\exceldb.xls;Extended Properties=""Excel 8.0;HDR=Yes;IMEX=1"""
Dim conn As New OleDbConnection(connstr)
conn.Open()
Dim da As New OleDbDataAdapter("select * from [Sheet1$]", conn)
Dim dt As New DataTable()
da.fill(dt)
For i As Integer = 0 To dt.Rows.Count - 1
'do your thing
next
conn.close()
Regards

How do you instantiate multiple sql connections to the same database via threading without getting an error?

I'm running a program where I call a function which creates a database connection and then runs a stored procedure. I call this function four times from four separate threads. I get an error (Login failed for user 'sa'. The user is not associated with a trusted SQL Server connection.
Exception Source:
.Net SqlClient Data Provider)
when I use multiple threads, but if I have the threads run one after another I have no problem.
Below is my code.
Dim comExecuteInsert As New SqlCommand
Dim comm As New SqlConnection
If (Not comm Is Nothing) Then
comm = Nothing
End If
comm = NewConnection(Conversion.ServerBox.SelectedText, "TESTAAA")
Try
comm.Open()
Catch ex As Exception
MsgBox(ex.ToString)
End Try
comExecuteInsert.Connection = comm
comExecuteInsert.CommandType = CommandType.StoredProcedure
comExecuteInsert.CommandText = strProcedureName
comExecuteInsert.CommandTimeout = 260000
comExecuteInsert.Parameters.Add("#tableName", SqlDbType.VarChar, 100).Value = strTableName
comExecuteInsert.Parameters.Add("#filename", SqlDbType.VarChar, 500).Value = strFileName
comExecuteInsert.ExecuteScalar()
comExecuteInsert.Parameters.Clear()
comm.Close()
What version -- and more importantly, what edition -- of SQL Server are you using? Also, which version and edition of Windows are you running the SQL server on?
Some editions of SQL Server limit the number of active connections you can use at the same time, and some editions of Microsoft Windows limit the number of inbound connections that can be made at the same time.
I'm not exactly sure what the limits are. I'm sure the numbers are documented somewhere on Microsoft.com, though.
If you are using Windows 2008 Server and SQL Server 2008 Enterprise, you should be able to get thousands of simultaneous connections (you might have to worry about transactions and performance, though).
On the other hand, if you are using SQL Server Developer Edition on Windows XP Home Edition, you might not be able to have more than 5 connections at once. If ANYTHING ELSE is connecting to either Windows or SQL, that might count against your limit too - is someone using Remote Console to look at that computer? Do you have the drive mapped to your computer?