-1

IWhat i wanna do

So I tried this code but it coudnt get a connection with the Database. I the connection string is correct

SqlConnection con = new SqlConnection("server=localhost;uid=root;database=menucreator");


        con.Open();

        SqlCommand cmd = new SqlCommand();

        cmd.CommandText = "insert into [kunde]Vorname()values(@nm)";

        cmd.Parameters.AddWithValue("@nm", Vorname.Text);
        cmd.Connection = con;

        SqlCommand cmdd = new SqlCommand();

        cmdd.CommandText = "insert into [kunde]Nachname()values(@nmm)";

        cmdd.Parameters.AddWithValue("@nmm", Nachname.Text);
        cmdd.Connection = con;

        int a = cmd.ExecuteNonQuery();

        if (a == 1)
        {
            MessageBox.Show("Dateien bitte");

        }
Bradley Grainger
  • 27,458
  • 4
  • 91
  • 108

1 Answers1

0

follow the following code. It inserts two columns into a table (tableName). Maintain proper space in SQL query as showing in below sample code. ALso, it's best practice to keep the code in a try-catch block to capture any error that occurs during DB operation.

 try
        {
            SqlConnection con = new SqlConnection("server=localhost;uid=root;database=menucreator");
            con.Open();
            SqlCommand cmd = new SqlCommand();
            cmd.CommandText = "insert into tableName(column1,column2) values(@nm,@nmm)";
            cmd.Parameters.AddWithValue("@nm", Vorname.Text);
            cmd.Parameters.AddWithValue("@nmm", Nachname.Text);
            cmd.Connection = con;
            int a = cmd.ExecuteNonQuery();
            if (a == 1)
            {
                MessageBox.Show("Dateien bitte");

            }
        }
        catch (Exception ex)
        {
            MessageBox.Show("Error:"+ex.ToString());
        }
tajinder singh
  • 113
  • 1
  • 10
  • The problem is in con.Open(); it says that their is no connection possibel with the database – Hamed Radhouani Jun 05 '21 at 16:41
  • This is an issue with you connection string you are passing to SqlConnection for connecting to DB. First, try to connect the server in SQL server management studio and make sure SSMS able to connect to DB using said credentials. Alternatevily you can connect the SqlServer in Visual studio and then can copy the connection string from there (Server Explorer) For info to copy the connection string please follow: [link](https://stackoverflow.com/questions/10479763/how-to-get-the-connection-string-from-a-database) – tajinder singh Jun 05 '21 at 17:56
  • Also in your connection string, you are not mentioning the password Standard connection string should be like this: `Server=myServerAddress;Database=myDataBase;User Id=myUsername;Password=myPassword;` – tajinder singh Jun 05 '21 at 18:03
  • There is no password . and i even tried your connection string but i still dont have a connection to the database. – Hamed Radhouani Jun 06 '21 at 12:07