How do I refer to SQL Server database with SqlDataAdapter - sql

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.

Related

How to find out SQL Server default instance name?

I have three SQL server instances on my computer. How can I find out which is the default one?
var conn = new SqlConnection("Data Source=.;Initial Catalog=SampleDb;Integrated Security=True")
I want to learn when I use '.' as above which database I will use.
You can only have more than one instance per OS installation if all of them have different instance names. The data source property has the format
HOST\INSTANCENAME
You are connecting to the default instance (of which there can only be one).

Connect SQL Express 2012 vb.net

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

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

CLR in SQL SERVER

I am a bit confused about SQL CLR. When i use the below query , then am i using CLR?
SqlCommand cmd =
new SqlCommand(
"SELECT * from items where name like '" + textBox1.Text + "%'", conn);
SqlDataReader reader = cmd.ExecuteReader();
Please provide a simple explanation of SQL CLR with some real example
No, you are using ADO.NET from a .NET program (running on the CLR) to query a SQL database.
Except from the textBox1.Text part this could have been code running in SQL CLR.
SQL CLR is like stored procedures written in c# or VB.NET. The documentation provides a couple of examples.
The context of SQL CLR refers to using managed .NET code as the language for programmability inside your database. If you where to deploy that code to SQL server as a DLL then I believe you would be "using the CLR" in the context of your question.

Query Timeout Settings in Excel

new to the site I'd like to give it a shot and see if I can get any answers regarding SQL Querys in Excel.
Is there a way to handle if a Timeout occurs in Microsoft Excel (mostly 2007/2010 on Win XP/Vista/7)? As you know you can connect Excel to a Microsoft SQL Server and run your query via Excel. The only thing is that I don't seem to find any Timeout options for this. And for an example, if there is a bad query, this might lock other tables in the SQL Server (2005) database.
I'm not looking for a script. It's more like settings I need and if possible I would like to add these Timeout settings to a specific Windows user account. Settings in either SQL Server 2005 or in Microsoft Excel 2007/2010.
Best regards
/Henrik
Use the CommandTimeout property
Dim objCommand As ADODB.Command
Set objCommand = New ADODB.Command
objCommand.CommandTimeout = 99 '
objCommand.ActiveConnection = cnConn
objCommand.CommandText = "DELETE Users WHERE IdLevel < 98"
objCommand.Execute