I have installed Visual Studio Ultimate, and installed the Microsoft SQL Server, and tried to find my way around it, using some tutorials I found on line.
I have successfully compiled and run the following C# code:
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
SqlConnection sql = new SqlConnection("Data Source=.\\SQLEXPRESS;Integrated Security=True;User Instance=True");
sql.Open();
SqlCommand command = new SqlCommand("CREATE DATABASE newDatabase;", sql);
command.ExecuteNonQuery();
command.CommandText = "CREATE TABLE newTable (name VARCHAR(20), age INT)";
command.ExecuteNonQuery();
command.CommandText = "INSERT INTO newTable VALUES ('John', 29)";
command.ExecuteNonQuery();
command.CommandText = "INSERT INTO newTable VALUES ('Jack', 21)";
command.ExecuteNonQuery();
command.CommandText = "INSERT INTO newTable VALUES ('Robin', 22)";
command.ExecuteNonQuery();
command.CommandText = "SELECT * FROM newTable;";
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
Console.WriteLine("{0} is {1} years old.",reader.GetString(0), reader.GetValue(1));
}
reader.Close();
sql.Close();
Console.ReadLine();
}
}
}
This will produce the right output, but now I want to actually see the newDatabase data-base. So I search for the keyword 'sql', and found the 'Microsoft SQL Server Managment Studio', and opened it.
Unfortunately, I couldn't find my database there under Databases:
Where is it hiding and how can I find it?
You need to attach this new database. On Databases, "right-click", and attach Database. Browse to the C# project folder defined when you created your project with visual studio and you will find it in the folder.
Update
In case you want to define the path directly to avoid searching you can have look on this example which might help you:
String str;
SqlConnection myConn = new SqlConnection ("Data Source=.\\SQLEXPRESS;Integrated Security=True;User Instance=True");
str = "CREATE DATABASE MyDatabase ON PRIMARY " +
"(NAME = MyDatabase_Data, " +
"FILENAME = 'C:\\MyDatabaseData.mdf', " +
"SIZE = 2MB, MAXSIZE = 10MB, FILEGROWTH = 10%) " +
"LOG ON (NAME = MyDatabase_Log, " +
"FILENAME = 'C:\\MyDatabaseLog.ldf', " +
"SIZE = 1MB, " +
"MAXSIZE = 5MB, " +
"FILEGROWTH = 10%)";
SqlCommand myCommand = new SqlCommand(str, myConn);
try
{
myConn.Open();
myCommand.ExecuteNonQuery();
}
catch (System.Exception ex)
{
Console.Write(ex.ToString());
}
finally
{
if (myConn.State == ConnectionState.Open)
{
myConn.Close();
}
}
Related
what you see bellow is a part of my WPF project I used it to backup/restore my SQL server database and it works great but; when I want to make a setup file by advanced installer and I move MDF and LDF files created by SQL script to app directory to use in SQL express it doesn't work. Now I want to know what can I do with connection string so that backup/restore prosses can work correctly
private string connectionString = "Data Source=.\\SQLEXPRESS;AttachDbFileName=|DataDirectory|\\DBNBO.mdf;Database=DBNBO; Trusted_Connection=Yes;";
private void BtnBackup_OnClick(object sender, EventArgs e)
{
SqlConnection connection = new SqlConnection(connectionString);
string database = connection.Database;
string query = "Backup Database [" + database + "] To Disk = '" + txtBackup.Text + "\\DB_backup.bak'";
SqlCommand command = new SqlCommand(query, connection);
connection.Open();
command.ExecuteNonQuery();
connection.Close();
}
private void btnRestore_Click(object sender, EventArgs e)
{
SqlConnection connection = new SqlConnection(connectionString);
string database = connection.Database;
if (connection.State != ConnectionState.Open) connection.Open();
string query1 = string.Format("Alter Database [" + database + "] Set Single_User With Rollback Immediate");
SqlCommand command1 = new SqlCommand(query1, connection);
command1.ExecuteNonQuery();
string query2 = string.Format("Use Master Restore Database [" + database + "] From Disk = '" + txtRestore.Text + "' With Replace");
SqlCommand command2 = new SqlCommand(query2, connection);
command2.ExecuteNonQuery();
string query3 = string.Format("Alter Database [" + database + "] Set Multi_User");
SqlCommand command3 = new SqlCommand(query3, connection);
command3.ExecuteNonQuery();
connection.Close();
}
I got this code inside a method:
string tableName = "messages_user-test";
OleDbConnection conn = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\Users\\janke\\source\\repos\\Unichat\\Unichat\\bin\\Debug\\history.accdb;Persist Security Info=False;");
conn.Open();
OleDbCommand comm = new OleDbCommand();
comm.Connection = conn;
string writestring = "insert into " + tableName + " ([from], [to], [datetime], [message]) values (#from, #to, #datetime, #message);";
Console.WriteLine(writestring);
comm.CommandText = writestring;
comm.Parameters.AddWithValue("#from", from);
comm.Parameters.AddWithValue("#to", to);
comm.Parameters.AddWithValue("#datetime", date);
comm.Parameters.AddWithValue("#message", text);
comm.ExecuteNonQuery();
comm.Dispose();
conn.Close();
When I execute the program I get this error at comm.ExecuteNonQuery();
System.Data.OleDb.OleDbException: "Syntaxerror in INSERT INTO statement."
I am pretty new to OleDB and I have already read hundreds of threads about this error but nothing worked for me.
Using square bracket for table name and field name
Maybe the date (from, to, date) value that causing the error
Don't forget to add try..catch
Check the profiler for more detail
using (OleDbConnection conn = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\Users\\janke\\source\\repos\\Unichat\\Unichat\\bin\\Debug\\history.accdb;Persist Security Info=False;"))
{
string strFeedback = "";
string tableName = "messages_user-test";
string writestring = string.Format("INSERT INTO [{0}] ([from], [to], [datetime], [message]) VALUES (#from, #to, #datetime, #message);", tableName);
OleDbCommand comm = new OleDbCommand(writestring);
comm.Parameters.Add(new OleDbParameter("#from", from.ToString("yyyy-MM-dd")));
comm.Parameters.Add(new OleDbParameter("#to", to.ToString("yyyy-MM-dd")));
comm.Parameters.Add(new OleDbParameter("#date", date.ToString("yyyy-MM-dd HH:mm:ss")));
comm.Parameters.Add(new OleDbParameter("#message", text));
try
{
strFeedback = comm.ExecuteNonQuery().ToString() + " record has been added successfully!";
}
catch (Exception ex)
{
strFeedback = "ERROR: " + err.Message;
}
}
I am extremely new to C# web development (or any development for that matter) but I am trying to figure out how to save the results from a SQL query to a variable. I think I understand the process, but many of the examples I am finding on the Web use a SqlConnection statement. My copy of Visual Studio does not seem to have that command (pretty sure I am using the wrong word here). What am I missing either softwarewise or knowledgewise accomplish my task?
Thank you in advance for your help.
Dep
It depends on what you want to do: insert, update, get data. It also depends if you want to use an ORM library or not. I all depends. The code that I copy below is an example of how to retrieve a DataTable using Ado.Net (as you mentioned SqlConnection):
You have to use:
using System.Data;
using System.Data.SqlClient;
This is the code for retrieving a DataTable
private DataSet ExecuteDataset(string query)
{
var conn = new SqlConnection("Data Source=" + Server + ";Initial Catalog=" + Database + ";User Id=" + Username + ";Password=" + Password + ";");
DataSet ds;
try
{
conn.Open();
ds = new DataSet();
var da = new SqlDataAdapter(query, conn);
da.Fill(ds);
}
catch (Exception)
{
throw;
}
finally
{
conn.Dispose();
conn.Close();
}
return ds;
}
private DataSet ExecuteDataset(string query, SqlParameter[] parametros)
{
var conn = new SqlConnection("Data Source=" + Server + ";Initial Catalog=" + Database + ";User Id=" + Username + ";Password=" + Password + ";");
DataSet ds;
try
{
conn.Open();
SqlCommand command = conn.CreateCommand();
command.CommandText = query;
foreach (SqlParameter p in parametros)
{
command.Parameters.Add(p);
}
ds = new DataSet();
var da = new SqlDataAdapter(command);
da.Fill(ds);
}
catch (Exception)
{
throw;
}
finally
{
conn.Dispose();
conn.Close();
}
return ds;
}
This is the code for running a query that does not expect result with and without parameters:
private void ExecuteNonQuery(string query)
{
var conn = new SqlConnection("Data Source=" + Server + ";Initial Catalog=" + Database + ";User Id=" + Username + ";Password=" + Password + ";");
try
{
conn.Open();
SqlCommand command = conn.CreateCommand();
command.CommandText = query;
command.ExecuteNonQuery();
}
catch (Exception)
{
throw;
}
finally
{
conn.Dispose();
conn.Close();
}
}
private void ExecuteNonQuery(string query, SqlParameter[] parametros)
{
var conn = new SqlConnection("Data Source=" + Server + ";Initial Catalog=" + Database + ";User Id=" + Username + ";Password=" + Password + ";");
try
{
conn.Open();
SqlCommand command = conn.CreateCommand();
command.CommandText = query;
foreach (SqlParameter p in parametros)
{
command.Parameters.Add(p);
}
command.ExecuteNonQuery();
}
catch (Exception)
{
throw;
}
finally
{
conn.Dispose();
conn.Close();
}
}
Here is the simplest example I can think of, take note of the using statements and comments
using System;
using System.Data;
using System.Data.SqlClient;
namespace DataAccess
{
class Program
{
static void Main(string[] args)
{
//Use your database details here.
var connString = #"Server=localhost\SQL2014;Database=AdventureWorks2012;Trusted_Connection=True;";
//Enter query here, ExecuteScalar returns first column first row only
//If you need to return more records use ExecuteReader/ExecuteNonQuery instead
var query = #"SELECT [AccountNumber]
FROM [Purchasing].[Vendor]
where Name = #Name";
string accountNumber = string.Empty;
//Using statement automatically closes the connection so you don't need to call conn.Close()
using (SqlConnection conn = new SqlConnection(connString))
{
SqlCommand cmd = new SqlCommand(query, conn);
//Replace #Name as parameter to avoid dependency injection
cmd.Parameters.Add("#Name", SqlDbType.VarChar);
cmd.Parameters["#name"].Value = "Michael";
try
{
conn.Open();
//Cast the return value to the string, if it's an integer then use (int)
accountNumber = (string)cmd.ExecuteScalar();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
Console.WriteLine(accountNumber);
//ReadKey just to keep the console from closing
Console.ReadKey();
}
}
}
If you are really new to C# with SQL Server, I would recommend to start from scratch using one of the tutorials shown here. It provides a lot of information in a step-by-step manner:
The basics
Clearly definition of the core ceoncepts
How to setup dependencies to get started
How to choose between development models (code, model vs. database first)
How to write queries
and much more.
Using SqlConnection is a valid choice, but requires more effort in writing the queries for doing basic stuff like selecting, updating, deleting or inserting data. You actually have to construct the queries and take care to build and dispose the commands.
On a related note:
The new way of doing all database-related activities in C# or .NET would be to harness Entity Framework (EF), and try to move away from any ADO.NET-based code. The latter still exists and hasn't been marked as obsolete, though. You may want to use ADO.NET for small apps or for any PoC tasks. But, otherwise, EF is the way to go.
EF is an ORM, and is indeed built as a repository pattern and generates a conceptual layer for us to work with. All of the nuances of the connection and command are completely encapsulated from us. This way, we don't have to meddle with these bare-bones.
If you want to do it well, you have to edit a file named Web.config in your project and put something like this inside (with your own DB data):
<connectionStrings >
<add
name="myConnectionString"
connectionString="Server=myServerAddress;Database=myDataBase;User ID=myUsername;Password=myPassword;Trusted_Connection=False;"
providerName="System.Data.SqlClient"/>
</connectionStrings>
Then, in the code, you can use it with:
SqlConnection con = new SqlConnection(
WebConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString);
Finally you can do that you want with "con", for example:
string queryString = "SELECT name, surname FROM employees";
SqlCommand command = new SqlCommand(queryString, con);
con.Open();
SqlDataReader reader = command.ExecuteReader();
try
{
while (reader.Read())
{
Console.WriteLine(String.Format("{0}, {1}",
reader["name"], reader["surname"]));
}
}
finally
{
reader.Close();
}
i use this nuget library.
https://www.nuget.org/packages/SqlServerDB_dotNET/
using SqlServerDB;
string server = #"INSTANCE\SQLEXPRESS";
string database = "DEMODB";
string username = "sa";
string password = "";
string connectionString = #"Data Source="+ server + ";Initial Catalog="+ database + "; Trusted_Connection=True;User ID="+ username + ";Password="+ password + "";
DBConnection db_conn = new DBConnection(connectionString);
Console.WriteLine("IsConnected: " + db_conn.IsConnected());
if (db_conn == null || !db_conn.IsConnected())
{
Console.WriteLine("Connessione non valida.");
return;
}
string sql = "SELECT ID, Message FROM Logs ORDER BY IDLic;";
DataTable dtLogs = db_conn.SelectTable(sql);
if (dtLogs == null || dtLogs.Rows.Count == 0)
return;
// Loop with the foreach keyword.
foreach (DataRow dr in dtLogs.Rows)
{
Console.WriteLine("Message: " + dr["Message"].ToString().Trim());
}
How can I check if a table already exists before creating a new one?
Updated Code:
private void checkTable()
{
string tableName = quotenameTxt.Text + "_" + firstTxt.Text + "_" + surenameTxt.Text;
string connStr = #"Data Source=|DataDirectory|\LWADataBase.sdf";
// SqlCeConnection conn = new SqlCeConnection(connStr);
// if (conn.State == ConnectionState.Closed) { conn.Open(); }
using (SqlCeConnection conn = new SqlCeConnection(connStr))
{
conn.Open();
SqlCeCommand cmd = new SqlCeCommand(#"SELECT *
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_NAME = #tname", conn);
cmd.Parameters.AddWithValue("#tname", tableName);
SqlCeDataReader reader = cmd.ExecuteReader();
if(reader.Read()){
MessageBox.Show("Table exists");}
else{
MessageBox.Show("Table doesn't exist");
createtable();}
Sql Server Compact supports the INFORMATION_SCHEMA views
using (SqlCeConnection conn = new SqlCeConnection(connStr))
{
conn.Open();
SqlCeCommand cmd = new SqlCeCommand(#"SELECT TOP 1 *
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_NAME = #tname", conn);
cmd.Parameters.AddWithValue("#tname", tableName)
SqlCeDataReader reader = cmd.ExecuteReader();
if(reader.Read())
Console.WriteLine("Table exists");
else
Console.WriteLine("Table doesn't exist");
}
EDIT
In version 3.5 it seems that the TOP 1 instruction is not accepted. However, given the WHERE clause it should make no difference using it or not so, to make it work just change the query to
SqlCeCommand cmd = new SqlCeCommand(#"SELECT * FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_NAME = #tname", conn);
SECOND EDIT
Looking at the code that creates the table.
(It is In chat, I suggest to add it to the question for completeness)
using (SqlCeCommand command = new SqlCeCommand(
"CREATE TABLE ['" + tableName + "'] " +
"(Weight INT, Name NVARCHAR, Breed NVARCHAR)", con))
The single quotes around the tableName variables becomes part of the name of the table. But the check for table exists doesn't use the quotes. And your code fall through the path that tries to create again the table with the quotes. Just remove the quotes around the name. They are not needed.
You can use the SqlClientConnection to get list of all objects in the db.
private void checkTable()
{
string tableName = quotenameTxt.Text + "-" + firstTxt.Text + "-" + surenameTxt.Text;
string connStr = #"Data Source=|DataDirectory|\LWADataBase.sdf";
using (SqlCeConnection conn = new SqlCeConnection(connStr))
{
bool isTableExist = conn.GetSchema("Tables")
.AsEnumerable()
.Any(row => row[2] == tableName);
}
if (!isTableExist)
{
MessageBox.Show("No such data table exists!");
}
else
{
MessageBox.Show("Such data table exists!");
}
}
Source: https://stackoverflow.com/a/3005157/1271037
I am creating a project in which I need to run 2-3 SQL commands in a single SQL connection.
Here is the code I have written:
SqlConnection con = new SqlConnection(#"Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\project.mdf;Integrated Security=True");
con.Open();
SqlCommand cmd = new SqlCommand("select * from " + mytags.Text + " ", con);
SqlDataReader rd = cmd.ExecuteReader();
if (rd.Read())
{
con.Close();
con.Open();
SqlCommand cmd1 = new SqlCommand("insert into " + mytags.Text + " values ('fname.lname#gmail.com','" + TextBox3.Text + "','" + TextBox4.Text + "','" + TextBox5.Text + "','"+mytags.Text+"')", con);
cmd1.ExecuteNonQuery();
label.Visible = true;
label.Text = "Date read and inserted";
}
else
{
con.Close();
con.Open();
SqlCommand cmd2 = new SqlCommand("create table " + mytags.Text + " ( session VARCHAR(MAX) , Price int , Description VARCHAR(MAX), Date VARCHAR(20),tag VARCHAR(10))", con);
cmd2.ExecuteNonQuery();
con.Close();
con.Open();
SqlCommand cmd3 = new SqlCommand("insert into " + mytags.Text + " values ('" + Session + "','" + TextBox3.Text + "','" + TextBox4.Text + "','" + TextBox5.Text + "','" + mytags.Text + "')", con);
cmd3.ExecuteNonQuery();
label.Visible = true;
label.Text = "tabel created";
con.Close();
}
I have tried to remove the error and I got that the connection is not going to else condition. Please review the code and suggest if there is any mistake or any other solution for this.
Just change the SqlCommand.CommandText instead of creating a new SqlCommand every time. There is no need to close and reopen the connection.
// Create the first command and execute
var command = new SqlCommand("<SQL Command>", myConnection);
var reader = command.ExecuteReader();
// Change the SQL Command and execute
command.CommandText = "<New SQL Command>";
command.ExecuteNonQuery();
The following should work. Keep single connection open all time, and just create new commands and execute them.
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
using (SqlCommand command1 = new SqlCommand(commandText1, connection))
{
}
using (SqlCommand command2 = new SqlCommand(commandText2, connection))
{
}
// etc
}
Just enable this property in your connection string:
sqb.MultipleActiveResultSets = true;
This property allows one open connection for multiple datareaders.
I have not tested , but what the main idea is: put semicolon on each query.
SqlConnection connection = new SqlConnection();
SqlCommand command = new SqlCommand();
connection.ConnectionString = connectionString; // put your connection string
command.CommandText = #"
update table
set somecol = somevalue;
insert into someTable values(1,'test');";
command.CommandType = CommandType.Text;
command.Connection = connection;
try
{
connection.Open();
}
finally
{
command.Dispose();
connection.Dispose();
}
Update:
you can follow
Is it possible to have multiple SQL instructions in a ADO.NET Command.CommandText property? too
This is likely to be attacked via SQL injection by the way. It'd be worth while reading up on that and adjusting your queries accordingly.
Maybe look at even creating a stored proc for this and using something like sp_executesql which can provide some protection against this when dynamic sql is a requirement (ie. unknown table names etc). For more info, check out this link.
No one has mentioned this, but you can also separate your commands using a ; semicolon in the same CommandText:
using (SqlConnection conn = new SqlConnection(connString))
{
using (SqlCommand comm = new SqlCommand())
{
comm.Connection = conn;
comm.CommandText = #"update table ... where myparam=#myparam1 ; " +
"update table ... where myparam=#myparam2 ";
comm.Parameters.AddWithValue("#myparam1", myparam1);
comm.Parameters.AddWithValue("#myparam2", myparam2);
conn.Open();
comm.ExecuteNonQuery();
}
}
Multiple Non-query example if anyone is interested.
using (OdbcConnection DbConnection = new OdbcConnection("ConnectionString"))
{
DbConnection.Open();
using (OdbcCommand DbCommand = DbConnection.CreateCommand())
{
DbCommand.CommandText = "INSERT...";
DbCommand.Parameters.Add("#Name", OdbcType.Text, 20).Value = "name";
DbCommand.ExecuteNonQuery();
DbCommand.Parameters.Clear();
DbCommand.Parameters.Add("#Name", OdbcType.Text, 20).Value = "name2";
DbCommand.ExecuteNonQuery();
}
}
Here you can find Postgre example, this code run multiple sql commands (update 2 columns) within single SQL connection
public static class SQLTest
{
public static void NpgsqlCommand()
{
using (NpgsqlConnection connection = new NpgsqlConnection("Server = ; Port = ; User Id = ; " + "Password = ; Database = ;"))
{
NpgsqlCommand command1 = new NpgsqlCommand("update xy set xw = 'a' WHERE aa='bb'", connection);
NpgsqlCommand command2 = new NpgsqlCommand("update xy set xw = 'b' where bb = 'cc'", connection);
command1.Connection.Open();
command1.ExecuteNonQuery();
command2.ExecuteNonQuery();
command2.Connection.Close();
}
}
}
using (var connection = new SqlConnection("Enter Your Connection String"))
{
connection.Open();
using (var command = connection.CreateCommand())
{
command.CommandText = "Enter the First Command Here";
command.ExecuteNonQuery();
command.CommandText = "Enter Second Comand Here";
command.ExecuteNonQuery();
//Similarly You can Add Multiple
}
}
It worked for me.