hallo there
This is a very basic question. I am currently a student and have done ASP.NET with C#.
For our purposes it was required to do work with an access database where connecting to it and adding data etc.was very easy.
My feeling is that access is not used much in the real world and would just like to enquire on the easiest and most correct way of establishing a connection to Microsoft Sql Server Database(Transact sql).
In my case the database is called dbActivities with primary data file being dbActivitiesData.mdf.
OleDbDataConnection conn;
conn = new OleDbConnection = #"Provider=Microsoft.Jet.Oledb.4.0:"
#"Data Source=DataBase.mdb";
conn.Open();
Regards
My feeling is that access is not used much in the real world
Unfortunately Access is still very much used in the real world :-)
As far as the correct way is concerned I would recommend you wrapping the connection into a using block to ensure proper handling:
class Program
{
static void Main()
{
var connectionString = #"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\work\DataBase.mdb";
using (var conn = new OleDbConnection(connectionString))
using (var cmd = conn.CreateCommand())
{
conn.Open();
cmd.CommandText = "SELECT Name FROM Customers";
using (var reader = cmd.ExecuteReader())
{
while (reader.Read())
{
var customerName = reader.GetString(reader.GetOrdinal("Name"));
Console.WriteLine(customerName);
}
}
}
}
}
And as far as Microsoft SQL Server is concerned:
var connectionString = #"Data Source=myServerAddress;Initial Catalog=myDataBase;User Id=myUsername;Password=myPassword;";
using (var conn = new SqlConnection(connectionString))
using (var cmd = conn.CreateCommand())
{
conn.Open();
cmd.CommandText = "SELECT Name FROM Customers";
using (var reader = cmd.ExecuteReader())
{
while (reader.Read())
{
var customerName = reader.GetString(reader.GetOrdinal("Name"));
Console.WriteLine(customerName);
}
}
}
string strSQLCommand;
SqlCommand command;
SqlConnection conn = null;
conn =new SqlConnection("Data Source=serverName\IP;Initial Catalog=dbActivities;UID=User;PWD=Password;Max Pool Size=500;");
strSQLCommand = "Your Command";
command = new SqlCommand(strSQLCommand, conn);
command.ExecuteNonQuery();
conn.Close();
Related
I have an SQL script select [master].[dbo].sp_SearchDuplicatedAddress('','','','') that I can invoke successfully from management studio. The function sp_SearchDuplicatedAddress exists in master database and is accessible by the logged user, no problem here. The problem arises when I try to execute that SQL script from ADO.Net I get the following error:
System.Data.SqlClient.SqlException: 'Cannot find either column "master" or the user-defined function or aggregate "master.dbo.sp_SearchDuplicatedAddress", or the name is ambiguous.'
And here's the code of sample app:
var conn = new SqlConnection();
var cmd = conn.CreateCommand();
cmd.CommandText = "select [master].[dbo].sp_SearchDuplicatedAddress('','','','')";
conn.Open();
var outt = cmd.ExecuteScalar();
}
Any idea how can I execute cross database queries from ADO.Net?
No repro for me. Can you modify the below to reproduce the behavior?
using Microsoft.Data.SqlClient;
using System;
namespace SqlClientTest
{
class Program
{
static void Main(string[] args)
{
var constr = "server=localhost;database=master;integrated security=true";
using (var conn = new SqlConnection(constr))
{
var cmd = conn.CreateCommand();
cmd.CommandText = #"
create or alter function dbo.sp_SearchDuplicatedAddress ( #a varchar(20),#b varchar(20),#c varchar(20),#d varchar(20) )
returns int
as
begin
return 3;
end ";
conn.Open();
cmd.ExecuteNonQuery();
}
constr = "server=localhost;database=tempdb;integrated security=true";
using (var conn = new SqlConnection(constr))
{
var cmd = conn.CreateCommand();
cmd.CommandText = "select [master].[dbo].sp_SearchDuplicatedAddress('','','','')";
conn.Open();
var outt = cmd.ExecuteScalar();
Console.WriteLine(outt);
}
}
}
}
I tried to get data in a drop down list and it's not working. I don't understand what's the problem.
string connString = #" Data Source=(LocalDB)\v11.0;AttachDbFilename='C:\Users\oshri\Documents\Stock scores.mdf';Integrated Security=True;Connect Timeout=30";
string queryLecturer = "select name_student from student";
SqlConnection conn = new SqlConnection(connString);
//SqlCommand cmdL = new SqlCommand(queryLecturer, conn);
conn.Open();
//SqlCommand SQLCommand = new SqlCommand();
//cmdL.CommandType = CommandType.Text;
//SQLCommand.CommandText = queryLecturer;
//conn.Close();
SqlDataAdapter adapter = new SqlDataAdapter(queryLecturer, conn);
adapter.Fill(subjects);
DropDownListID.DataSource = subjects;
DropDownListID.DataBind();
DropDownListID.DataBind();
conn.Close();
You are assigning a DataSet containing DataRowView items to your drop down. Your drop down (is it a System.Windows.Forms.ComboBox?) is not smart enough to extract the real values from this DataSet. Instead, use a SqlDataReader to read your string values and add them to a list that you can use as data source for your drop down.
string connString = #"Data Source=...";
string queryLecturer = "select name_student from student";
using (var conn = new SqlConnection(connString))
using (var cmd = new SqlCommand(queryLecturer)) {
conn.Open();
using (SqlDataReader reader = cmd.ExecuteReader()) {
var list = new List<string>();
while (reader.Read()) {
list.Add(reader.GetString(0)); // 0 is the column index.
}
DropDownListID.DataSource = list;
}
}
The using statements automatically close the connection and dispose resources at the end of the statement blocks. They do so even if the statement blocks are left prematurely because of an exception or because of a break or return statement.
I have just installed Postgre SQL on Windows 10. I can connect to the data base via PSQL and pgAdmin fine.
The problem is that I can neither connect to the data base using C# or an .udl-test file.
My C# code:
var connection = new SqlConnection(
"Data Source=localhost;" +
"User id=postgres;" +
"Password=postgres;" +
"connection timeout=10");
connection.Open();
This gives me an exception (server not found).
SqlConnection is for SQL Server only. You could use NpgsqlConnection from Npgsql library. Simple example from library developers:
var connString = "Host=myserver;Username=mylogin;Password=mypass;Database=mydatabase";
using (var conn = new NpgsqlConnection(connString))
{
conn.Open();
// Insert some data
using (var cmd = new NpgsqlCommand())
{
cmd.Connection = conn;
cmd.CommandText = "INSERT INTO data (some_field) VALUES (#p)";
cmd.Parameters.AddWithValue("p", "Hello world");
cmd.ExecuteNonQuery();
}
// Retrieve all rows
using (var cmd = new NpgsqlCommand("SELECT some_field FROM data", conn))
using (var reader = cmd.ExecuteReader())
while (reader.Read())
Console.WriteLine(reader.GetString(0));
}
http://www.npgsql.org/doc/index.html
So I'm developing a web application where each user has it's own database. What i want is to automate the process of create the user specific database when he registers.
My idea is to create a new empty database with a custom name and then run a pre-made sql script to generate the tables and default values for this database.
Edit
I think I haven't been clear before.
I create the database as follows:
using (var conn = new SqlConnection("data source=MySource; uid=MyUser; pwd=MyPassword;"))
{
using (var cmd = new SqlCommand())
{
conn.Open();
cmd.Connection = conn;
cmd.CommandText = "Create Database MYNewDB;";
cmd.ExecuteNonQuery();
}
}
Is there a way to (after this) execute the scripts saved in .sql file to create the tables and values for this new data base?
found the solution on this answer.
using (var conn = new SqlConnection("data source=MySource; initial catalog=MYNewDB;persist security info=True;user id=MyUser;password=MyPassword;multipleactiveresultsets=True; "))
{
string script = File.ReadAllText(#"C:\Somewhere\...\script.sql");
// split script on GO command
IEnumerable<string> commandStrings = Regex.Split(script, #"^\s*GO\s*$", RegexOptions.Multiline | RegexOptions.IgnoreCase);
conn.Open();
foreach (string commandString in commandStrings)
{
if (commandString.Trim() != "")
{
using (var command = new SqlCommand(commandString, conn))
{
command.ExecuteNonQuery();
}
}
}
conn.Close();
}
What's the simplest way to connect and query a database for a set of records in C#?
#Goyuix -- that's excellent for something written from memory.
tested it here -- found the connection wasn't opened. Otherwise very nice.
using System.Data.OleDb;
...
using (OleDbConnection conn = new OleDbConnection())
{
conn.ConnectionString = "Provider=sqloledb;Data Source=yourServername\\yourInstance;Initial Catalog=databaseName;Integrated Security=SSPI;";
using (OleDbCommand cmd = new OleDbCommand())
{
conn.Open();
cmd.Connection = conn;
cmd.CommandText = "Select * from yourTable";
using (OleDbDataReader dr = cmd.ExecuteReader())
{
while (dr.Read())
{
Console.WriteLine(dr["columnName"]);
}
}
}
}
Very roughly and from memory since I don't have code on this laptop:
using (OleDBConnection conn = new OleDbConnection())
{
conn.ConnectionString = "Whatever connection string";
using (OleDbCommand cmd = new OleDbCommand())
{
cmd.Connection = conn;
cmd.CommandText = "Select * from CoolTable";
using (OleDbDataReader dr = cmd.ExecuteReader())
{
while (dr.Read())
{
// do something like Console.WriteLine(dr["column name"] as String);
}
}
}
}
That's definitely a good way to do it. But you if you happen to be using a database that supports LINQ to SQL, it can be a lot more fun. It can look something like this:
MyDB db = new MyDB("Data Source=...");
var q = from db.MyTable
select c;
foreach (var c in q)
Console.WriteLine(c.MyField.ToString());
This is an alternative way (DataReader is faster than this one):
string s = "";
SqlConnection conn = new SqlConnection("Server=192.168.1.1;Database=master;Connect Timeout=30;User ID=foobar;Password=raboof;");
SqlDataAdapter da = new SqlDataAdapter("SELECT TOP 5 name, dbid FROM sysdatabases", conn);
DataTable dt = new DataTable();
da.Fill(dt);
for (int i = 0; i < dt.Rows.Count; i++)
{
s += dt.Rows[i]["name"].ToString() + " -- " + dt.Rows[i]["dbid"].ToString() + "\n";
}
MessageBox.Show(s);
If you are intending on reading a large number of columns or records it's also worth caching the ordinals and accessing the strongly-typed methods, e.g.
using (DbDataReader dr = cmd.ExecuteReader()) {
if (dr.Read()) {
int idxColumnName = dr.GetOrdinal("columnName");
int idxSomethingElse = dr.GetOrdinal("somethingElse");
do {
Console.WriteLine(dr.GetString(idxColumnName));
Console.WriteLine(dr.GetInt32(idxSomethingElse));
} while (dr.Read());
}
}
If you are querying a SQL Server database (Version 7 and up) you should replace the OleDb classes with corresponding classes in the System.Data.SqlClient namespace (SqlConnection, SqlCommand and SqlDataReader) as those classes have been optimized to work with SQL Server.
Another thing to note is that you should 'never' select all as this might lead to unexpected results later on if you add or remove columns to this table.
I guess, you can try entity framework.
using (SchoolDBEntities ctx = new SchoolDBEntities())
{
IList<Course> courseList = ctx.GetCoursesByStudentId(1).ToList<Course>();
//do something with courselist here
}
Charge the libraries
using MySql.Data.MySqlClient;
This is the connection:
public static MySqlConnection obtenerconexion()
{
string server = "Server";
string database = "Name_Database";
string Uid = "User";
string pwd = "Password";
MySqlConnection conect = new MySqlConnection("server = " + server + ";" + "database =" + database + ";" + "Uid =" + Uid + ";" + "pwd=" + pwd + ";");
try
{
conect.Open();
return conect;
}
catch (Exception)
{
MessageBox.Show("Error. Ask the administrator", "An error has occurred while trying to connect to the system", MessageBoxButtons.OK, MessageBoxIcon.Error);
return conect;
}
}