简体   繁体   中英

How to add/edit/retrieve data using Local Database file in Microsoft Visual Studio 2012

I want to get into developing applications that use databases. I am fairly experienced (as an amateur) at web based database utilization (mysql, pdo, mssql with php and old style asp) so my SQL knowledge is fairly good.

Things I have done already..

  • Create forms application
  • Add four text boxes (first name, last name, email, phone)
  • Added a datagrid control
  • Created a database connection using 'Microsoft SQL Server Database File (SqlClient)'
  • Created a table with fields corresponding to the four text boxes.

What I want to be able to do now is, when a button is clicked, the contents of the four edit boxes are inserted using SQL. I don't want to use any 'wrapper' code that hides the SQL from me. I want to use my experience with SQL as much as possible.

So I guess what I am asking is how do I now write the necessary code to run an SQL query to insert that data. I don't need to know the SQL code obviously, just the c# code to use the 'local database file' connection to run the SQL query.

An aside question might be - is there a better/simpler way of doing this than using the 'Microsoft SQL Server Database File' connection type (I have used it because it looks like it's a way to do it without having to set up an entire sql server)

This first example is an over view based upon how I think it will be easier to understand but this is not a recommended approach due to vulnerability to SQL injection (a better approach further down). However, I feel it is easier to understand.

private void InsertToSql(string wordToInsert)
  {
        string connectionString = Data Source=myServerAddress;Initial Catalog=myDataBase;Integrated Security=SSPI; User ID=myDomain\myUsername;Password=myPassword;

        string queryString = "INSERT INTO table_name (column1) VALUES (" + wordToInsert + ")"; //update as you feel fit of course for insert/update etc

    using (SqlConnection connection = new SqlConnection(connectionString))
    {
        connection.Open()
        SqlDataAdapter adapter = new SqlDataAdapter();
        SqlCommand command = new SqlCommand(queryString, connection);        

        command.ExecuteNonQuery();
        connection.Close();
    }
}

I would also suggest wrapping it in a try/catch block to ensure the connection closes if it errors.

I am not able to test this but I think it is OK!

Again don't do the above in live as it allows SQL injection - use parameters instead. However, it may be argued it is easier to do the above if you come from PHP background (just to get comfortable).

This uses parameters:

public void Insert(string customerName)
{
try
   {
    string connectionString = Data Source=myServerAddress;Initial Catalog=myDataBase;Integrated Security=SSPI; User ID=myDomain\myUsername;Password=myPassword;

    using (SqlConnection connection = new SqlConnection(connectionString))
    {
    connection.Open();
    connection.Open() SqlCommand command = new SqlCommand( "INSERT INTO Customers (CustomerName" + "VALUES (@Name)", connection);

    command.Parameters.Add("@Name", SqlDbType.NChar, 50, " + customerName +");
    command.ExecuteNonQuery();
    connection.Close();
    }
 catch()
 {
     //Logic in here
 }
 finally()
 {
    if(con.State == ConnectionState.Open)
    {
        connection.Close();
    }
 }

}

And then you just change the SQL string to select or add!

The below is inserting data using parameters which I believe is a better approach:

            var insertSQL = "INSERT INTO yourTable (firstName, lastName, email, phone) VALUES (firstName, lastName, email, phone)";

            string connectionString = "Data Source=myServerAddress;Initial Catalog=myDataBase;Integrated Security=SSPI; User ID=userid;Password=pwd;"

            using (var cn = new SqlCeConnection(connectionString))
            using (var cmd = new SqlCeCommand(insertSQL, cn))
            {
                cn.Open();

                cmd.Parameters.Add("firstName", SqlDbType.NVarChar);
                cmd.Parameters.Add("lastName", SqlDbType.NVarChar);
                cmd.Parameters.Add("email", SqlDbType.NVarChar);
                cmd.Parameters.Add("phone", SqlDbType.NVarChar);

                cmd.Parameters["firstName"].Value = firstName;
                cmd.Parameters["lastName"].Value = lastName;
                cmd.Parameters["email"].Value = email;
                cmd.Parameters["phone"].Value = phone;
                cmd.ExecuteNonQuery();

            }

This is selecting data from database and populating datagridview:

            var dt = new DataTable();

            string connectionString = "Data Source=myServerAddress;Initial Catalog=myDataBase;Integrated Security=SSPI; User ID=userid;Password=pwd;"

            using (var cn = new SqlCeConnection(connectionString )
            using (var cmd = new SqlCeCommand("Select * From yourTable", cn))
            {
                cn.Open();

                using (var reader = cmd.ExecuteReader())
                {
                    dt.Load(reader);

                    //resize the DataGridView columns to fit the newly loaded content.
                    yourDataGridView.AutoSize = true;                                       yourDataGridView.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.AllCells);

                    //bind the data to the grid
                    yourDataGridView.DataSource = dt;
                }
            }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM