0

I am just wondering how can I check if a database exists in C# using ADO.net without EF. please advise .thanks so much

Below is my Controller

[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult Create(string Name, string ID)
{
      string myConnectionString;
      DataTable dt = new DataTable();
      //connect DB
      myConnectionString = "Data Source=xxxxxx"
      //Validation   
    if (ModelState.IsValid)
    {
        using (SqlConnection sqlConn = new
        SqlConnection(myConnectionString))
        {
            string sql = "insert into [DB] (ID,Name) Values('" + ID + "','" + Name + ")";
            using (SqlCommand sqlCmd = new SqlCommand(sql, sqlConn))
            {
                sqlCmd.CommandType = CommandType.Text;
                sqlConn.Open();
                using (SqlDataAdapter sqlAdapter = new
                    SqlDataAdapter(sqlCmd))
                {
                    sqlAdapter.Fill(dt);
                }
            }
        }
    }
}
Mehran Gharzi
  • 136
  • 1
  • 10
ericso
  • 109
  • 1
  • 9
  • 1
    Use this link: https://stackoverflow.com/questions/2232227/check-if-database-exists-before-creating – hassan.ef Dec 01 '20 at 05:13
  • thanks you for your advice. Reference above link. it is not working for my code.sad – ericso Dec 01 '20 at 07:13
  • Does this answer your question? [Update if the name exists else insert - in SQL Server](https://stackoverflow.com/questions/39249746/update-if-the-name-exists-else-insert-in-sql-server). The link hassan.ef cited checks if the *database* exists; it doesn't check if a *record* exists. – paulsm4 Dec 02 '20 at 03:24

0 Answers0