this is my connection class, i know i am going to put the ip, or i am in a error ? the direction of internet? what do i go to put? can i do it with web service? what is the form easy for to do it? here my connection class...
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.SqlClient;
namespace MisNotas.Conexiones
{
class Conexion
{
public SqlConnection conectar()
{
SqlConnection con = new SqlConnection(#"Data Source=.\sqlexpress;Initial Catalog=misnotas;Integrated Security=True");
return con;
}
public void EjecutarConsulta(SqlCommand comando)
{
comando.Connection.Open(); // open connection
comando.ExecuteNonQuery(); // execute the query
comando.Connection.Close(); // close the connection
}
}
}
The idea is since another place, i can to start session and to do queries and edits... how to do it?
it is in windows application not in asp.net.. thanks
i will put diferents tags for the import is how to do it... thanks
I think the question is how to access a database on a different machine, if that is the case - you can specifiy the IP address or name of the remote machine in the connection string:
public SqlConnection Conectar(string remoteMachine)
{
SqlConnection con = new SqlConnection(string.Format(#"Data Source={0}\sqlexpress;Initial Catalog=misnotas;Integrated Security=True", remoteMachine));
return con;
}
Note however you still have to figure out security, i.e. integrated security might not work remotely - for a full list of the options with examples check out this link.
I think you are asking about the database connection string?
"server=123.123.123.123;database=database_name;user=user_name;password=password"
That is the basic that works for just about any ADO accessible database, but of course, if you are accessing a server where the Windows NTLM mechanism such that the user identity under which your software is a user for that database can work, Integrated Security = true is best.
Related
Doing a university project that requires an application that stores and outputs data from a local access DB file.
So far I have very little C# knowledge but I have a basic understanding of how to write code and what functions and methods are.
I have looked up a lot of different questions on StackOverflow and other sites about this kind of issue, yet I could not find a solution to my problem.
Here is the code -
private void search_db(object sender, EventArgs e)
{
using (SqlConnection conn = new SqlConnection())
{
string search_query = search_input.Text;
conn.ConnectionString = "Data Source=D:/Projects/WIP/8515/Academy/Travel Agency C#/Hotel_Agency/Hotel_Database.accdb;";
conn.Open();
SqlCommand command = new SqlCommand("SELECT * FROM Customers WHERE (name LIKE #query) OR (EGN LIKE #query)", conn);
command.Parameters.Add(new SqlParameter("query", search_query));
// Create new SqlDataReader object and read data from the command.
using (SqlDataReader reader = command.ExecuteReader())
{
// while there is another record present
while (reader.Read())
{
// write the data on to the screen
Console.WriteLine(String.Format("{0} \t | {1} \t | {2} \t | {3}",
// call the objects from their index
reader[0], reader[1], reader[2], reader[3]));
}
}
}
}
on line 6 of the given code, if my ConnectionString which provides the data souce which I have triple checked and confirmed is proper, the only thing I'm not sure is what type of slash should I use, since the default \ slash from windows directories gets mistaken for an escape by Visual Studio, while with the / slash its ok.
The problem is the connection to the DB always fails with this error
An unhandled exception of type 'System.Data.SqlClient.SqlException'
occurred in System.Data.dll
Additional information: A network-related or instance-specific error
occurred while establishing a connection to SQL Server. The server was
not found or was not accessible. Verify that the instance name is
correct and that SQL
Here is the full list of the namespaces we are using for this application
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
I have tried adding provider keyword to the connection string but that leads to another error about an unsupported keyword, since the System.Data.SqlClient namespace is allegedly automatically setting a provider.
Any help as to what might be causing this is appreciated!
PS: I apologize for any further lack of knowledge I present, I really am new to C# programming, but I find it quite interesting and exciting, and would like to learn more.
You are making a common mistake here. The classes defined in the namespace System.Data.SqlClient (SqlConnection, SqlCommand etc.) are able to talk only with a Sql Server database system (Full, Express or LocalDb). They cannot work with an Access database.
For this database you should use the classes in the System.Data.OleDb namespace (OleDbConnection, OleDbCommand etc.) These classes understand the connectionstring to reach an Access database and can open and work with it.
So your code should be:
....
using System.Data.OleDb;
private void search_db(object sender, EventArgs e)
{
using (OleDbConnection conn = new OleDbConnection())
{
conn.ConnectionString = ......
conn.Open();
string cmdText = #"SELECT *
FROM Customers
WHERE ([name] LIKE #q1) OR (EGN LIKE #q2)";
using(OleDbCommand command = new OleDbCommand(cmdText, conn))
{
command.Parameters.Add("#q1", OleDbType.VarWChar).Value = search_query;
command.Parameters.Add("#q2", OleDbType.VarWChar).Value = search_query;
using (OleDbDataReader reader = command.ExecuteReader())
{
....
}
}
}
}
An importat thing to remember with OleDb is that you have positional parameters. The parameters are not recognized by their name but by their position in the query text. So if you have two parameters placeholder, even if they are for the same value, you need to put two parameters in the collection. One for the first placeholder and one for the second placeholder. This is even more important when you have placeholders for different values. You need to add the values in the exact order in which they are expected in the query text.
Below is a concise version of my code as it pertains to db access.
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
namespace DataAccess
{
public class DbConnection
{
public string connString = "Data Source=[Insert IP];Initial Catalog=MOSAIQ;Persist Security Info=True;User ID=[Insert User];Password=[Insert Password]";
public void CreateConnection()
{
using (SqlConnection conn = new SqlConnection(connString))
{
try
{
conn.Open();
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
}
}
}
For security reason I've removed IP and user credentials. That being said I copied the above connection string directly from the properties of the server explorer which successfully connected to my db.
While stepping through this code the following error is caught upon executing conn.Open()
Seems pretty obvious that there is an issue during validation. The credentials supplied are those used for SQL authentication.
Why is it that I can connect via server explorer but not directly via my code? What does Visual Studio's do for me that I can't seemingly do myself?
Ports are open, firewall is not an issue. I'm stumped and as a rookie in this matter would appreciate further guidance.
I'm trying to connect to SQL Server 2008 R2, using Visual Studio's 2013.
As a test try to use the SqlConnectionStringBuilder
System.Data.SqlClient.SqlConnectionStringBuilder builder = new System.Data.SqlClient.SqlConnectionStringBuilder();
builder["Data Source"] = "(local)";
builder["integrated Security"] = true;
//Or Supply User and Password
builder["Connect Timeout"] = 1000;
builder["Initial Catalog"] = "AdventureWorks;NewValue=Bad";
Console.WriteLine(builder.ConnectionString);
If you do that and are still experiencing the error then move on to testing the networking.
<add name="RM_V1.0CS1" connectionString="Data Source=SERVER;Initial Catalog=DB;User ID=sa;Password=Password" providerName="System.Data.SqlClient" />
Edit Explicitly Set Provider:
For those that might experience similar issues. I save my solutions on a network drive through work. Because I was opening and running my solution from this network location for a reason I'm yet unaware of it was using my windows credentials instead of the SQL credentials that I was passing to the SQL server. Once the solution was moved to my local workstation the method ran as expected. Any insight as to what more specifically was occurring would be of interest.
Hello there I hope you're having a great time.
I have a question And I will break it down into 3 points:
1: create a class to connect to sql server the connection should be made using sql server authentication.
This class should contain several variables for connection parameters.
2: create a user form that shows the current connection parameters. And allow the user to update those parameters. In this form there should be a button to test the connect and another button to save the user changes to the connection parameters.
3: how to share the connection, created by the class we made in point 1, between different forms in the application. Without keeping too many open connections ideally only one connection should be open.
I will add the code that can solve this problem I hope that you can help me refine it.
I am new to all of this.
Thank you all for help.
already exists; SqlConnection and maybe SqlConnectionStringBuilder
that kinda already exists, via the IDE, but last time I checked this was not a redistributable dll. You could, however, simply hook a SqlConnectionStringBuilder to a PropertyGrid - or just write the UI from scratch
even "only one connection should be open" is wrong, IMO - let the inbuilt connection pooling deal with that; all you need is some configuration class with the connection string - and just deal with the connections as you need them, very locally - i.e.
using(var conn = new SqlConnection(Config.ConnectionString))
{
conn.Open();
// NOT SHOWN: do a couple of related operations
} // <== and here, it dies
1 : go to MSDN website you'll find what you need :
http://msdn.microsoft.com/fr-fr/library/system.data.sqlclient.sqlcommand.aspx?cs-save-lang=1&cs-lang=csharp#code-snippet-2
private static void ReadOrderData(string connectionString)
{
string queryString =
"SELECT OrderID, CustomerID FROM dbo.Orders;";
using (SqlConnection connection = new SqlConnection(
connectionString))
{
SqlCommand command = new SqlCommand(
queryString, connection);
connection.Open();
SqlDataReader reader = command.ExecuteReader();
try
{
while (reader.Read())
{
Console.WriteLine(String.Format("{0}, {1}",
reader[0], reader[1]));
}
}
finally
{
// Always call Close when done reading.
reader.Close();
}
}
}
2: look at your connection properties (http://msdn.microsoft.com/en-us/library/System.Data.SqlClient.SqlConnection_properties.aspx) and fill a listView or equivalent with it
3: Use previous SqlConnection.Open() to deal with it
i am using this example to connect c# to sql server. can you please tell me what i have to include in order to be able to use sqlconnection?
it must be something like:
using Sqlconnection; ???
string connectionString = #"Data Source=.\SQLEXPRESS;AttachDbFilename=""C:\SQL Server 2000 Sample Databases\NORTHWND.MDF"";Integrated Security=True;Connect Timeout=30;User Instance=True";
SqlConnection sqlCon = new SqlConnection(connectionString);
sqlCon.Open();
string commandString = "SELECT * FROM Customers";
SqlCommand sqlCmd = new SqlCommand(commandString, sqlCon);
SqlDataReader dataReader = sqlCmd.ExecuteReader();
while (dataReader.Read())
{
Console.WriteLine(String.Format("{0} {1}", dataReader["CompanyName"], dataReader["ContactName"]));
}
dataReader.Close();
sqlCon.Close();
using System.Data;
using System.Data.SqlClient;
If you use SQL Server 2005 or SQL Server 2008 and use C# then you must provide the following namespace.
using System.Data;
using System.Data.SqlClient;
One nice trick one when you don't know what namespace to use in using statement. Type the classname (e.g. SqlConnection, MemoryStream, FileStream, etc), then press Ctrl+.. Though it won't work if the classname doesn't match the case, e.g. Sqlconnection, sqlconnection
Also, check out connectionstrings.com - it's probably the most useful tech website on the internet for making sure your ADO.NET is set up right.
When you decide to move on from just using Northwind, that site will come in handy a bunch. No one I know actually remembers the syntax for a connection string.
Just include the following namespace:-
using System.Data.SqlClient;
What is the the best practice for SQL connections?
Currently I am using the following:
using (SqlConnection sqlConn = new SqlConnection(CONNECTIONSTRING))
{
sqlConn.Open();
// DB CODE GOES HERE
}
I have read that this is a very effective way of doing SQL connections. By default the SQL pooling is active, so how I understand it is that when the using code ends the SqlConnection object is closed and disposed but the actual connection to the DB is put in the SQL connection pool. Am i wrong about this?
That's most of it. Some additional points to consider:
Where do you get your connection string? You don't want that hard-coded all over the place and you may need to secure it.
You often have other objects to create as well before your really use the connection (SqlCommand, SqlParameter, DataSet, SqlDataAdapter), and you want to wait as long as possible to open the connection. The full pattern needs to account for that.
You want to make sure your database access is forced into it's own data layer class or assembly. So a common thing to do is express this as a private function call:
.
private static string connectionString = "load from encrypted config file";
private SqlConnection getConnection()
{
return new SqlConnection(connectionString);
}
And then write your sample like this:
using (SqlConnection sqlConn = getConnection())
{
// create command and add parameters
// open the connection
sqlConn.Open();
// run the command
}
That sample can only exist in your data access class. An alternative is to mark it internal and spread the data layer over an entire assembly. The main thing is that a clean separation of your database code is strictly enforced.
A real implementation might look like this:
public IEnumerable<IDataRecord> GetSomeData(string filter)
{
string sql = "SELECT * FROM [SomeTable] WHERE [SomeColumn] LIKE #Filter + '%'";
using (SqlConnection cn = getConnection())
using (SqlCommand cmd = new SqlCommand(sql, cn))
{
cmd.Parameters.Add("#Filter", SqlDbType.NVarChar, 255).Value = filter;
cn.Open();
using (IDataReader rdr = cmd.ExecuteReader())
{
while (rdr.Read())
{
yield return (IDataRecord)rdr;
}
}
}
}
Notice that I was also able to "stack" the creation of the cn and cmd objects, and thus reduce nesting and only create one scope block.
Finally, a word of caution about using the yield return code in this specific sample. If you call the method and don't complete your DataBinding or other use right away it could hold the connection open for a long time. An example of this is using it to set a data source in the Load event of an ASP.NET page. Since the actual data binding event won't occur until later you could hold the connection open much longer than needed.
Microsoft's Patterns and Practices libraries are an excellent approach to handling database connectivity. The libraries encapsulate most of the mechanisms involved with opening a connection, which in turn will make your life easier.
Your understanding of using is correct, and that method of usage is the recommended way of doing so. You can also call close in your code as well.
Also : Open late, close early.
Don't open the connection until there are no more steps left before calling the database. And close the connection as soon as you're done.