如何将Visual Studio文本框中的数据导入数据库?

时间:2013-11-21 15:28:58

标签: c# asp.net sql database

我似乎无法将信息插入到文本字段中以转到数据库。这是我到目前为止所拥有的。

**public class DBConnectivity
{
    private static DbConnection GetConnection()
    {
        string connString;
        //  change to your connection string in the following line
        connString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=I:\Applications Coursework\quiz.accdb";
        return new DbConnection(connString);
    }

    //method that saves a user in the db
    public static void SaveName(string a, string b, string c)
    {
        DbConnection myConnection = DBConnectivity();
        string myQuery = "INSERT INTO user( user_name,  user_age, user_country ) VALUES ( '" + a + "' , " + b + ",  " + c + " )";
        OleDbCommand myCommand = new DbCommand(myQuery, myConnection);
        try
        {
            myConnection.Open();
            myCommand.ExecuteNonQuery();
        }
        catch (Exception ex)
        {
            Console.WriteLine("Exception in DBHandler", ex);
        }
        finally
        {
            myConnection.Close();
        }
    }**

protected void Button1_Click(object sender, EventArgs e)
{
    string a = TxbName.Text;
    string b = TxbAge.Text ;
    string c = TxbCountry.Text; 
    DBConnectivity.cs (a, b, c);

}
}

1 个答案:

答案 0 :(得分:0)

试试这个?

 public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            String a = TxbName.Text;
            String b = TxbAge.Text ;
            String c = TxbCountry.Text; 

            String Constring = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=I:\Applications Coursework\quiz.accdb";
            String cmdinsert = @"INSERT INTO user( user_name,  user_age, user_country) VALUES ( @a, @b, @c )";
            OleDbConnection con = new OleDbConnection (Constring);
            OleDbDataAdapter da = new OleDbDataAdapter();
            OleDbCommand cmd = new OleDbCommand(cmdinsert, con);


            try
            {
                da.InsertCommand.Parameters.Add("@a", OleDbType.VarChar, 15);
                da.InsertCommand.Parameters["a"].Value = TxbName.Text;
                da.InsertCommand.Parameters.Add("@b", OleDbType.VarChar, 15);
                da.InsertCommand.Parameters["b"].Value = TxbAge.Text;
                da.InsertCommand.Parameters.Add("@c", OleDbType.VarChar, 15);
                da.InsertCommand.Parameters["c"].Value = TxbCountry.Text;

                con.Open();
                da.InsertCommand.ExecuteNonQuery();
                MessageBox.Show("Worked");
                con.Close();

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }



        }
    }
}

这是指向OLEdb插入命令http://msdn.microsoft.com/en-us/library/system.data.oledb.oledbdataadapter.insertcommand%28v=vs.110%29.aspx

的MSDN的链接