I am beginner at SQL and thank you for your attention. I've created a database (by using "Add new Item" from "Project" menu and adding a "Service Based Database") in Visual Studio 2015 and now I want to connect to it and read or write data on it.
But I don't know how to connect to it by code.
I use the string showed in the connection string when I click on the database in server explorer.
That is here:
Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename="c:\users\soroush\documents\visual studio 2015\Projects\databasetest2\databasetest2\Database1.mdf";Integrated Security=True
But as you know, it cannot be used when I copy and paste it to a string thah can be used in new sqlConnection(connection string), because this string has '\' or ' " '
What's the right string for me to connect to this local database?
Now this is my code but it is not useful:
private void button1_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(#"Data Source = (LocalDB)\MSSQLLocalDB; AttachDbFilename = c:\users\soroush\documents\visual studio 2015\Projects\databasetest2\databasetest2\Database1.mdf; Integrated Security = True");
con.Open();
string t=#"INSERT INTO Table (Id,name) Values (34, 'John')";
SqlCommand cmd = new SqlCommand(t, con);
cmd.ExecuteNonQuery();
con.Close();
}
private void button2_Click(object sender, EventArgs e)
{
using (SqlConnection con = new SqlConnection(#"Data Source = (LocalDB)\MSSQLLocalDB; AttachDbFilename = c:\users\soroush\documents\visual studio 2015\Projects\databasetest2\databasetest2\Database1.mdf; Integrated Security = True"))
{
con.Open();
string t = "SELECT * From Table";
SqlCommand cmd = new SqlCommand(t, con);
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
MessageBox.Show(reader["Id"].ToString() + reader["name"].ToString());
}
con.Close();
}
}
Thank you for your help
Update: I get another errors in writing and reading table
I think I've connected to my database after using your help. and now I have another error in reading the table. this error points to
SqlDataReader reader = cmd.ExecuteReader();
in my code and says:
An unhandled exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll Additional information: Incorrect syntax near the keyword 'Table'.
and an error in writing on table points to
cmd.ExecuteNonQuery();
in my code:
An unhandled exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll Additional information: Incorrect syntax near the keyword 'Table'.
My database has one table named Table that contains two columns: Id(int) and name(nchar10)
The code you're using to connect to your Sql db is .. well ... really old school. We just don't do it like that any more.
So - what can we do instead? Lets use a nice library called Dapper which makes 'talking' to a sql server really easy, simple and safer.
First, install the package Dapper from nuget:
Create a POCO which will represent the data that is returned from the DB.
public class Foo
{
public int Id { get; set; }
public string Name { get; set; }
}
Now update the form code as follows:
private const string _connectionString = #"Data Source = (LocalDB) <snipped..>";
private void button1_Click(object sender, EventArgs e)
{
string query = "INSERT INTO Table (Id,name) Values (34, 'John')";
int rowsInserted;
using (var db = new SqlConnection(_connectionString))
{
rowsInserted = db.Execute(query);
}
if (rowsInserted != 1)
{
// Log/Handle the fact that you failed to insert 1 record;
}
}
private void button2_Click(object sender, EventArgs e)
{
IList<Foo> foos;
using (var db = new SqlConnection(_connectionString))
{
const string query = "SELECT * FROM Table";
// This will always return a list. It's empty or has items in it.
foos = db.Query<Foo>(query).ToList();
}
foreach(var foo in foos)
{
MessageBox.Show($"{foo.Id} - {foo.Name}");
}
}
Is that much cleaner? Yep - I thought so.
Of course, I would never put database code behind a winform event but into a dedicated class, etc. But I guess you're just learning/playing around/experimenting :) :)
Also, I've not put error handling in there, to keep the example smallish.
Change:
string t = "SELECT * From Table";
to:
string t = "SELECT * From [Table]";
and:
string t=#"INSERT INTO Table (Id,name) Values (34, 'John')";
to:
string t=#"INSERT INTO [Table] (Id,name) Values (34, 'John')";
See https://stackoverflow.com/a/695590/34092 and https://learn.microsoft.com/en-us/sql/t-sql/language-elements/reserved-keywords-transact-sql .
my problem has been solved
at first for connection to database I typed an # before connection string and deleted the quotes inside the string as #juergen d said in comments
at second for solving the error in writing and reading the table I typed [ and ] before and after the "Table" as #mjwills said
also #Pure.Krome explained a more professional way to improve the code
thank you every body
Related
CONTEXT: I am writing a WPF app. It works with a SQL Server database in which I put some data, concretely the strings Titulo and Descripcion, the int XP and the string fotoMision. When I click a button the program is supposed to save this data in the database.
PROBLEM: when I click the button it throws me an exception in string connection's line showing that the object is not instanced. If I put these first lines right below the InitializeComponent(); line the second one doesn't recognise the miConexion string. Why does that happen and how can I fix it?
CODE:
static string miConexion = ConfigurationManager.ConnectionStrings["myProgress.Properties.Settings.DatosHabilidades"].ConnectionString;
SqlConnection miConexionSql = new SqlConnection(miConexion);
private void Button_Click(object sender, EventArgs e)
{
string consulta = "INSERT INTO datosMisiones (Titulo, Descripcion, XP, fotoMision) VALUES (tituloMision, descripcionMision, xpMision, nuestroIconoMision";
SqlCommand miSqlCommand = new SqlCommand(consulta, miConexionSql);
miConexionSql.Open();
miSqlCommand.Parameters.AddWithValue("#Titulo", tituloMision);
miSqlCommand.ExecuteNonQuery();
miConexionSql.Close();
}
Connections are meant to be short-lived, i.e. you should create one when the button is clicked and then dispose it right after you have executed the query. Using a using statement implicitly disposes the IDisposable:
private void Button_Click(object sender, EventArgs e)
{
const string Consulta = "INSERT INTO datosMisiones (Titulo, Descripcion, XP, fotoMision) VALUES (tituloMision, descripcionMision, xpMision, nuestroIconoMision";
string miConexion = ConfigurationManager.ConnectionStrings["myProgress.Properties.Settings.DatosHabilidades"].ConnectionString;
using (SqlConnection miConexionSql = new SqlConnection(miConexion))
using (SqlCommand miSqlCommand = new SqlCommand(Consulta, miConexionSql))
{
miConexionSql.Open();
miSqlCommand.Parameters.AddWithValue("#Titulo", tituloMision);
miSqlCommand.ExecuteNonQuery();
miConexionSql.Close();
}
}
The format of your connection string for a SQL Server Database should be like so:
"Data Source=DNS_or_IP_Address;Initial Catalog=DatabaseName;User Id=MyUser;Password=MyPassword"
Connection Strings and Examples for various databases
put connectionstring on form_load event
This error occurs whenever i'm trying to run my program.
Additional information: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ')' at line 1
The code is as follows:
private void create_Click(object sender, EventArgs e)
{
string MyConnectionString = "Server=x.x.x.x;Database=groupdes_New;Uid=root;Pwd=password;";
//create connection
MySqlConnection connection = new MySqlConnection(MyConnectionString);
//connect to database
connection.Open();
MySqlCommand cmd;
cmd = connection.CreateCommand();//create command
cmd.CommandText = "CREATE Table Newtable (" + "name" + ")";
cmd.ExecuteNonQuery();
if (connection.State == ConnectionState.Open)
{
connection.Close();
}
}
I still can't manage to solve this error. Thanks for the help!
Your create table sintaxis is wrong.
You need define field datatype
CREATE TABLE Table1
(`myDate` datetime)
;
Is there anything wrong with this code? Please help me out.
protected void Button_Click(object sender, EventArgs e)
{
string cs = "Data Source=SFSIND0402;Initial Catalog=TestDB;Integrated Security=SSPI;Provider=Microsoft.ACE.OLEDB.12.0";
OleDbConnection conn = new OleDbConnection(cs);
conn.Open();
OleDbCommand insert = conn.CreateCommand();
insert.CommandText="insert into Employee(ID, Name, Sex, Salary) values('003','Vedpathi','M',25000)";
insert.Connection = conn;
insert.ExecuteNonQuery();
conn.Close();
}
I am getting the following error:
Multiple-step OLE DB operation generated errors. Check each OLE DB status value, if available. No work was done
(on line 22:conn.Open();)
When connecting to an MS SQL database, use the MS SQL providers:
using (var connection = new SqlConnection(connectionString))
{
connection.Open();
var cmd = new SqlCommand(commandText, connection);
cmd.ExecuteNonQuery();
}
In addition to the solution Luaan mentioned, you should store your connection string in the config file of the app and also encrypt it.
Even if you use SSL encryption when communicating with the DB, an ill-indended person can extract the string variables, if he / she runs the application on his / her machine.
I've a form opened which is has loaded some sort of data (like username, CNIC, Contact no, etc etc) in Check boxes, now I want to update the data in such manner that I simply change the text in the text boxes and click on the save changes to save it. I've tried it but I am not able to do it in correct manner.
Let me show you how I've coded, the code I did in frmViewformList savechanges button is :
private void btnSaveChanges_Click(object sender, EventArgs e)
{
string sql;
string UserName;
UserName = txtUserName.Text; // saving data loaded on run time to UserName
sql = "";
sql += "UPDATE UserLogin";
sql += "SET Name = "+ //how to access data I've changed in TextBox after loading +"";
sql += "WHERE Name= " + //how to access data which was in text box right after loading + ""; //
}
I am a bit confused about how to refer to data, like the name already in the text box or the name which I have changed and how to write it in SQL query...
This question is a bit confusing, I know. Let me explain; the form is loaded, there are text boxes which is being populated with the data in database on load event, I change the data in text boxes and save on click so that the update query runs and changes the data in database as well.
I'm not able to create logic here how to do this, can any one help me out, I am sorry I am a new developer of C# that's why I am a bit confused.
You should use Sql Parameters in order to avoid SQL Injection which could leave your database vulnerable to malicious exploitation.
It's a good idea to separate the logic for performing the update to the logic where you create your query so you don't have to repeat code and so that you can maintain your code easier.
Here is an example you can reference:
public void DoWork()
{
// Build Query Use #Name Parameters instead of direct values to prevent SQL Injection
StringBuilder sql = new StringBuilder();
sql.Append("UPDATE UserLogin");
sql.Append("SET Name = #UpdatedName");
sql.Append("WHERE Name = #Name");
// Create parameters with the value you want to pass to SQL
SqlParameter name = new SqlParameter("#Name", "whatEverOldNameWas");
SqlParameter updatedName = new SqlParameter("#UpdatedName", txtUserName.Text);
Update(sql.ToString(), new [] { name, updatedName });
}
private static readonly string connectionString = "Your connection string"
private static readonly DbProviderFactory factory = DbProviderFactories.GetFactory("System.Data.SqlClient");
public static int Update(string sql, SqlParameter[] parameters)
{
try
{
using (DbConnection connection = factory.CreateConnection())
{
connection.ConnectionString = connectionString;
using (DbCommand command = factory.CreateCommand())
{
command.Connection = connection;
command.CommandText = sql;
foreach (var parameter in parameters)
{
if (parameter != null)
command.Parameters.Add(parameter);
}
connection.Open();
return command.ExecuteNonQuery();
}
}
}
catch (Exception)
{
throw;
}
}
You will want to strip all ', ", and ` characters out of your input so that people can't inject SQL. When you do SET Name = " +, you'll want to actually wrap whatever you're including in quotes because it's a string: SET Name = '" + UserName "' " +...
This is probably best done using
string.Format("UPDATE UserLogin SET Name = '{0}' WHERE Name = '{1}'", UserName, FormerUserName);
Then you will execute your query by using System.Data.SqlClient; and then work with SqlConnection to establish a connection to the server, and execute a SqlCommand of some kind; take a look at: http://www.codeproject.com/Articles/4416/Beginners-guide-to-accessing-SQL-Server-through-C
The following is a code snippet to insert data into database using ADO.NET and assuming SQL Server database.
At the top of your .cs file you should have.
using System.Data.SqlClient; // for sql server for other data bases you should use OleClient instead.
And inside your button click event you could put the following.
// to know how to get the right connection string please check this site: http://www.connectionstrings.com
string connString = "database connection string here";
using (SqlConnection con = new SqlConnection(connString))
{
con.Open();
//insert text into db
string sql_insert = "INSERT INTO ....."; // Use parameters here.
SqlCommand cmd_insert = new SqlCommand(sql_insert, con);
int rowsAffected = cmd_insert.ExecuteNonQuery();
}
Hopefully this is enough to get you started.
This is my simple Code which stores parameters value in variables and use it on query
but it's give me ERROR message "INVALID Object name "DTA010.DFDR00" because I guess i'm not connected with the AS/400
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
//string strQuery;
string order_no = Request.QueryString["order"];
if (order_no != null)
{
Response.Write("\n");
Response.Write("Order No is ");
Response.Write(order_no);
}
else
{
Response.Write("You Order number is not correct");
}
Response.Write("Your Order Status is");
Response.Write(niceMethod1());
Response.Write("\n");
}
public string niceMethod1()
{
string tDate = "";
string nOrder = (Request.QueryString["order"] ?? "0").ToString();
using (SqlConnection connection = new SqlConnection("Data Source=*****;User ID=web;Password=****;Initial Catalog=WEBSTATUS;Integrated Security=False;"))
{
string commandtext = "SELECT A.STAT01 FROM DTA010.DFDR00 AS A WHERE A.ORDE01 = #nOrder"; //#nOrder Is a parameter
SqlCommand command = new SqlCommand(commandtext, connection);
//command.Parameters.AddWithValue("#nPhone", nPhone); //Adds the ID we got before to the SQL command
command.Parameters.AddWithValue("#nOrder", nOrder);
connection.Open();
tDate = (string)command.ExecuteScalar();
} //Connection will automaticly get Closed becuase of "using";
return tDate;
}
}
The drivers needed to connect from a .NET application to a AS/400 are properly installed.
If the names of the schema (aka library) and table (aka file) are spelled correctly, try replacing the period with a slash /. This would be used for "system" naming syntax, rather than "standard" naming syntax.
You are definitely connected. I think the issue may be in the error you received. Make sure that the object exists that you are connecting to. WRKOBJ OBJ(BTGDTA010/DF01HDR00) will see if it exists. Check that everything is spelled right. It might be a typo.
Here is the simplest way I Found may be useful for someone..!!
First need to add Assembly IBM library and
using IBM.Data.DB2.iSeries;
then
iDB2Connection connDB2 = new iDB2Connection(
"DataSource=158.7.1.78;" +
"userid=*****;password=*****;DefaultCollection=MYTEST;");