简体   繁体   中英

How can I call the data from the database in C# and sql?

I am working on a school project in C# and SQL.

How can I make a condition in which if the first textbox is checked equals a word defined from inside the database it prints yes The idea is: The project is a library that sells school books for a specific town. In my project, there is a place to enter the price of books and define them in advance. For example, I put that the price of books for John's second grade is a hundred dollars. On the sales screen, I want him to print the price he entered (one hundred dollars) if he checks that in the combobox that the class is the second grade and the name of the school is John.

SqlDataAdapter adapt, adapt1;
DataTable dt;
con.Open();
adapt = new SqlDataAdapter("select * from pricing where lib_grade like'", con)
adapt1 = new SqlDataAdapter("select * from pricing where lib_schoolname like'", con);

if (comboBox2.SelectedItem==adapt|| comboBox4.SelectedItem == adapt1)
{
    MessageBox.Show("mission complete successfully");
}

I don't really understand what you want to do. But if you just want to check if a school name or grade exists in your table 'pricing' you can create the following method :

public class MyClass
{
    private static SqlConnection Connection= new SqlConnection(your_connection_string);
    private static SqlCommand;
    
    // This function allows to check if a given value exists in the given table and column
    public static bool Exists(string value, string table, string column)
    {
          bool exists = false;              

          Connection.Open();
          
          // Prepare the SQL command and then add parameters to prevent from SQL injection
          Command = new SqlCommand("SELECT COUNT(*) FROM @Table WHERE @Column LIKE @Value", Connection);
          Command.Parameters.Add("@Table", System.Data.SqlDbType.VarChar).Value = table;
          Command.Parameters.Add("@Column", System.Data.SqlDbType.VarChar).Value = column;
          Command.Parameters.Add("@Grade", System.Data.SqlDbType.VarChar).Value = grade;

          if((int)Command.ExecuteScalar() > 0) exists = true;
          
          Connection.Close();

          return exists;
    }
}

And then you can use it like that to check if a given school name exists in your database :

if(MyClass.Exists("Harvard", "pricing", "lib_schoolname"))
{
     // Harvard exists like school name in the database
}
else
{
     // Harvard doesn't exists like school name in the database
}

Or like that if you want to check if a grade exists in your database :

if(MyClass.Exists("Dr", "pricing", "lib_grade"))
{
     // Dr exists like grade in the database
}
else
{
     // Dr doesn't exists like grade in the database
}

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