I\'m coming over from PHP and am having a hard time with storing information into my newly created local database. I\'m using Microsoft Visual C# 2010 to help me learn and devel
Well, if you want a quick, almost close to the wire code like the way you used to have with PHP, the following code should work.
var conn = new SqlConnection("Your Connection String");
var command = conn.CreateCommand();
command.CommandText = "insert into sessions (id, name) values (@id, @name)";
command.Parameters.AddWithValue("@id", "");
command.Parameters.AddWithValue("@name", "test");
conn.Open();
command.ExecuteNonQuery();
command.Dispose();
conn.Close();
In the long run, it would be better if you get accustomed to one of the data-related / ORM frameworks such as Entity Framework, NHibernate and the likes. That would really help a lot in data manipulation and make your life a whole lot easier.
Here's some code that uses SQLServer to do a direct insert, although you'll need a connection string to your database.
Include the SQL server database includes.
using System.Data.SqlClient;
using System.Data.SqlTypes;
. . .
using (SqlConnection cn = new SqlConnection("XXXXX")) // must put a connection string to your database here
{
cn.Open();
using (SqlCommand cmd = new SqlCommand("INSERT INTO Session(field1, field2) VALUES(@Value1, @Value2)"))
{
cmd.Parameters.AddWithValue("@Value1", 4);
cmd.Parameters.AddWithValue("@Value2", "test");
cmd.ExecuteNonQuery();
}
}
There are many ways to access a database from your application. These range from low-level ado.net commands (SqlDataReader, etc..) to using an Object Relational Mapper (ORM) such as Entity Framework.
All of them will require that you learn the technologies, but you can start here:
http://windowsclient.net/learn/videos.aspx
It depends on your requirments, but for most situations, I would highly recommend you use Entity Framework or Linq to Sql data classes. You'd be much better off... go with the latter as a start... hope it helps.
[Edited]
If you want to see how easy an ORM can be:
Start using the entities like this:
using (DataClasses1DataContext db = new DataClasses1DataContext("Data Source=localhost\sqlexpress; Initial Catalog=myDBName; Integrated Security=true")) { IEnumerable citiesForUSA = db.Cities.Where(x => x.Country.Name == "United States");
City city = new City();
city.Name = "Metropolis";
//etc
db.Cities.InsertOnSubmit(city);
db.SubmitChanges(); // <-- INSERT INTO completed
//etc
}
Good luck!
:-)