Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
130 views
in Technique[技术] by (71.8m points)

c# - How do i add my customer data into a SQL database?

This is my CustomerRegister class, but I cant seem to input data from my addressTextBox into the CustomerTbl.

DataBase dbObj = new DataBase();

string selStr = "Update CustomerTbl Set customer_address = '" + addressTextBox.Text + "' Where custID = " + "NULL";
 int i = dbObj.ExecuteNonQuery(selStr);

This is my DataBase class but return comdObj.ExecuteNonQuery(); doesnt work as there is not such custID named NULL. So how do i program in such a way so that i am able to constantly update the database when a new user registers?

class DataBase
    {
        string connStr = @"Data Source=(LocalDB)MSSQLLocalDB;AttachDbFilename=D:OOPGBanking Mini Project RaynardBanking Mini Project RaynardDatabase1.mdf;Integrated Security = True";
        SqlConnection connObj;
        SqlCommand comdObj;
        SqlDataReader dR;

        public DataBase()
        {
            connObj = new SqlConnection(connStr);
            connObj.Open();
        }
        public SqlDataReader ExecuteReader(string selStr)
        {
            comdObj = new SqlCommand(selStr, connObj);
            dR = comdObj.ExecuteReader();
            return dR;
        }
        public int ExecuteNonQuery(string sqlStr)
        {
            comdObj = new SqlCommand(sqlStr, connObj);
            return comdObj.ExecuteNonQuery();
        }
    }
question from:https://stackoverflow.com/questions/65886182/how-do-i-add-my-customer-data-into-a-sql-database

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

First you should create a connection to SQL database before executing any query. After then you should be able to insert data before updating any data into database. After you insert data successfully you can update data using above command text. Here is some sample code for inserting data for registering customer.

using (SqlCommand command = new SqlCommand())
{
    command.Connection = connection;            // <== lacking
    command.CommandType = CommandType.Text;
    command.CommandText = "INSERT into CustomerTbl (CustId, Name, Address) VALUES (@CustId, @Name, @Address)";
    command.Parameters.AddWithValue("@CustId", name);
    command.Parameters.AddWithValue("@Name", userId);
    command.Parameters.AddWithValue("@Address", idDepart);

    try
    {
        connection.Open();
        int recordsAffected = command.ExecuteNonQuery();
    }
    catch(SqlException)
    {
        // error here
    }
    finally
    {
        connection.Close();
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...