Which is the best way to execute a query in C# + SQL Server CE? I need to create a table, but after 3 days of unsuccessful attempts, I realize that I really can't do it for myself... So I'm here asking for help.
I've tried these topics:
create sql table programmatically
Data Adapter Vs Sql Command
But all ways I tried show me an exception... I'm confused, where is my mistake?
My current code:
public void Connect()
{
try
{
string FileName = "DataBase";
using (SqlCeConnection myConnection = new SqlCeConnection(#"Data Source=|DataDirectory|\" + FileName + ".sdf;Password=Z123"))
{
string query = "create table EXP(ID int, source int)";
int i;
SqlCommand cmd = new SqlCommand(query, connection);
cmd.con.open();
i = cmd.ExecuteNonQuery();
}
}
catch (SqlCeException ae)
{
MessageBox.Show(ae.Message.ToString());
}
}
Many thanks!
If you're using SQL Server CE then you need to use a SqlCeCommand (not a SqlCommand - that's for the full-blown SQL Server).
So change your code to:
using (SqlCeConnection myConnection = new SqlCeConnection(#"Data Source=|DataDirectory|\" + FileName + ".sdf;Password=Z123"))
{
string query = "create table EXP(ID int, source int)";
// use SqlCeCommand here!! Also: use the "myConnection" SqlCeConnection you're
// opening at the top - don't use something else.....
SqlCeCommand cmd = new SqlCeCommand(query, myConnection);
myConnection.open();
cmd.ExecuteNonQuery();
myConnection.Close();
}
Related
Context: I'm developing an app for windows in Visual Studio that has a table of stock materials and another of buyed materials, both in a Sql Server.
I want that every time you buy something it is added into the stock table.
I'm new in using SQL with c# combined.
I'm trying this from a tutorial, but does nothing. Not even an exception.
string cmdString = "Insert INTO Table1 (Column_name) VALUES (#val1)";
string connString = #"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\Database.mdf;Integrated Security=True";
using (SqlConnection conn = new SqlConnection(connString))
{
using (SqlCommand comm = conn.CreateCommand())
{
comm.Connection = conn;
comm.CommandText = cmdString;
comm.Parameters.AddWithValue("#val1", Value);
try
{
conn.Open();
comm.ExecuteNonQuery();
conn.Close()
}
catch(SqlException ex)
{
}
}
}
Is this totally wrong or should i change something?
Edit: I figured out. I was inserting val1 in a column, but the ID was empty so it throws an NullId exception. For some reason in debug mode I wasn't able to see it.
Thanks for the help. If I have the Table1 with autoincrement why it needs an ID? There is a way that when something is inserted the Id generates automatically?
You can use this query to insert data like that :
{
if (con.State == ConnectionState.Open)
con.Close();
}
{
SqlCommand cmd0561 = new SqlCommand(#"insert into Table1 (value1,value1) values
(#value1,#timee)", con);
cmd0561.Parameters.AddWithValue("#value1", value1.Text.Trim);
cmd0561.Parameters.AddWithValue("#value2", value2.Text.Trim);
con.Open();
cmd0561.ExecuteNonQuery();
con.Close();
}
I have to delete/drop database from code written in C# using ado.net in desktop based application using window forms. The code is as follows,
string connectionString = Helpers.Configs.ApplicationConnectionString;
SqlConnection conn2 = new SqlConnection(connectionString);
connectionString = connectionString.Replace(conn2.Database, "master");
string query = "alter database [" + DBName + "] set single_user with rollback immediate; drop database [" + DBName + "];";
bool isTrue = false;
using (SqlConnection conn = new SqlConnection(connectionString))
{
SqlCommand cmd = new SqlCommand(query, conn);
cmd.CommandTimeout = 0;
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
isTrue = true;
}
return isTrue;
In above code, I am using master database to connect through and executing the query. In result, database is deleted somehow but the problem is, a messagebox/alert is showing in case of ExecuteNonQuery() which is as follows,
I don't want this messagebox or alert to be displayed. Because this very annoying that is displayed in application on deleting database.
I am trying to update an access table with the code noted below. however, the update does not execute. It doesn't give me any errors but it doesn't update the database. Any suggestions?
string Const = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=F:\\Db\\test.accdb";
OleDbCommand Cmd;
OleDbConnection con22 = new OleDbConnection(Const );
con22.Open();
string sql = "UPDATE CostT SET tFormSent='" + Selection1.Text + "',TName='" + UserName.Text + "',FormDate='" + FormDate.Text + "',where ReqNum=" + ReqNum.Text;
cmd = new OleDbCommand(sql, con22);
cmd.ExecuteNonQuery();
con22.Close();
MessageBox.Show("Form has been Updated");
Try changing the query
to
string sql = "UPDATE CostT SET tFormSent = #selection1,TName = #UserName,FormDate = #FormDate where ReqNum = #ReqNum";
cmd = new OleDbCommand(sql, con22);
cmd.Parameters.Add("#selection1", Selection1.Text);
cmd.Parameters.Add("#UserName", UserName.Text);
cmd.Parameters.Add("#FromDate", FromDate.Text);
cmd.Parameters.Add("#ReqNum", ReqNum.Text);
cmd.ExecuteNonQuery();
con22.Close();
Your query has a syntax error: you have a comma before your WHERE clause that does not belong there.
But more important: Your code is open to SQL injection! Please don't insert user input directly into your query, but use parameterized queries instead!
this code is successfully inserting a new value in a SQL db, but only when I insert constant values.
I need help where it says **(?)** in the code below, where I want to insert new values without specifying constants in the code.
What I mean is, I want to be able to type any random value in output window and it gets inserted into the SQL db.
private void InsertInfo()
{
String strConnection = "Data Source=HP\\SQLEXPRESS;database=MK;Integrated Security=true";
SqlConnection con = new SqlConnection(strConnection);
string connetionString = null;
SqlConnection connection ;
SqlDataAdapter adapter = new SqlDataAdapter();
connetionString = #"Data Source=HP\SQLEXPRESS;database=MK;Integrated Security=true";
connection = new SqlConnection(connetionString);
string sql = "insert into record (name,marks) **values( ?))";**
try
{
connection.Open();
adapter.InsertCommand = new SqlCommand(sql, connection);
adapter.InsertCommand.ExecuteNonQuery();
MessageBox.Show ("Row inserted !! ");
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
private void insert_Click(object sender, EventArgs e)
{
InsertInfo();
}
There is no need to use an adapter here; that is not helping you. Just:
var name = ...
var marks = ...
using(var conn = new SqlConnection(connectionString))
using(var cmd = conn.CreateCommand()) {
cmd.CommandText = "insert into record (name, marks) values (#name, #marks)";
cmd.Parameters.AddWithValue("name", name);
cmd.Parameters.AddWithValue("marks", marks);
conn.Open();
cmd.ExecuteNonQuery();
}
or with a tool like "dapper":
var name = ...
var marks = ...
using(var conn = new SqlConnection(connectionString)) {
conn.Open();
conn.Execute("insert into record (name, marks) values (#name, #marks)",
new {name, marks});
}
Those '?' are termed as parameters. From what I understand, you are wanting to use a parametrized query for your insert which is a good approach as they save you from chance of a SQL injection. The '?' sing in your query is used when you are using an
OLEDBConnection & Command object.
Normally, you would use '#' symbol to specify a parameter in your query. There is no need for an adapter. You just
//Bind parameters
// Open your Connection
// Execute your query
// Close connection
// return result
Parametrized queries 4 Guys from Rolla
MSDN: How to Protect from SQL injection in ASP.NET
I've created a database and a table with 2 fields Id and Name.
Now I want to insert values on clicking a button the sammple code is given. it's not working.
using (SqlConnection connection = new SqlConnection(strConnection))
{
SqlCommand command =new SqlCommand("insert into Test (Id,Name) values(5,kk);",connection);
connection.Open();
command.ExecuteNonQuery();
connection.Close();
}
String values should be in quotes. This has not much to do with C#, more with T-SQL
Try this, and notice the kk;
SqlCommand command =
new SqlCommand("insert into Test (Id,Name) values(5,'kk');",connection);
connection.Open();
command.ExecuteNonQuery();
connection.Close();
Also I am assuming here that Id is not an auto-increment field. If it is, then you should not fill it.
As a side-node you should look at parameterized queries to prevent SQL injection.
In this instance, you need single quotes ' around the kk
insert into Test (Id,Name) values(5,'kk')
In general, you should use parameterised queries
try this:
SqlConnection conn = new SqlConnection();
SqlTransaction trans = conn.BeginTransaction();
try
{
using (SqlCommand cmd = new SqlCommand("insert into Test (Id,Name) values(#iD, #Name)", conn, trans))
{
cmd.CommandType = CommandType.Text;
cmd.AddParameter(SqlDbType.UniqueIdentifier, ParameterDirection.Input, "#iD", ID);
cmd.AddParameter(SqlDbType.VarChar, ParameterDirection.Input, "#Name", Name);
cmd.ExecuteNonQuery();
}
conn.CommitTransaction(trans);
}
catch (Exception ex)
{
conn.RollbackTransaction(trans);
throw ex;
}
Try this:
SqlConnection con = new SqlConnection('connection string here');
string command = "INSERT INTO Test(Id, Name) VALUES(5, 'kk')";
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandType = System.Data.CommandType.Text;
cmd.CommandText = command;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
String values should be between ' '
Verify your connection string
//add your connection string between ""
string connectionString = "";
using (var conn = new SqlConnection(connectionString))
using (DbCommand cmd = conn.CreateCommand())
{
cmd.CommandText = "INSERT INTO pdf (Id, Name) VALUES (5, 'kk')";
conn.Open();
conn.ExecuteNonQuery();
conn.Close();
}
It looks like you have multiple problems with your current code.
You need to enclose string values in single quotes, as pointed out in other answers.
You need to enable remote connection to your SQL server.
Check the following link if you are using SQL server 2008.
How to enable remote connections in SQL Server 2008?
and for SQL Server 2005 see:
How to configure SQL Server 2005 to allow remote connections