I'm trying to make a INSERT
in MS SQL
, when running the code, there is no error, but does not INSERT
in sql, when running a script manually in sql it writes without any problem
I have tried both ways, which is also discussed.
private void InsertToDatabase(string Name, string Document, string Board, int Block, int apartment, string AuthorizedFrom, string DataEntry, string Comments)
{
try
{
SqlConnection connect = new SqlConnection(DBOConnect.connectionString);
SqlCommand cmd = new SqlCommand("INSERT INTO visitors (name, document, board, block, apartment, authorized_from, date_entry, username, comments) VALUES ('" + Name + "', '" + Document + "', '" + Board + "', '" + Block + "', '" + apartment + "', '" + AuthorizedFrom + "', '" + DataEntry + "', '" + Profile.LoginInformation[0].Username + "', '" + Comments + "')", connect);
connect.Open();
cmd.ExecuteNonQuery();
connect.Close();
//using (SqlConnection connect = new SqlConnection(DBOConnect.connectionString))
//using (SqlCommand cmd = connect.CreateCommand())
//{
// cmd.CommandText = @"INSERT INTO visitors (name, document, board, block, apartment, authorized_from, date_entry, username, comments) VALUES (@Name, @Document, @Board, @Block, @apartment, @AuthorizedFrom, @DataEntry, @Username, @Comments)";
// cmd.Parameters.AddWithValue("@Name", Name);
// cmd.Parameters.AddWithValue("@Document", Document);
// cmd.Parameters.AddWithValue("@Board", Board);
// cmd.Parameters.AddWithValue("@Block", Block);
// cmd.Parameters.AddWithValue("@apartment", apartment);
// cmd.Parameters.AddWithValue("@AuthorizedFrom", AuthorizedFrom);
// cmd.Parameters.AddWithValue("@DataEntry", DataEntry);
// cmd.Parameters.AddWithValue("@Username", Profile.LoginInformation[0].Username);
// cmd.Parameters.AddWithValue("@Comments", Comments);
// connect.Open();
// cmd.ExecuteNonQuery();
// connect.Close();
//}
}
catch (SqlException ex)
{
System.Media.SystemSounds.Exclamation.Play();
var frmMain = System.Windows.Application.Current.Windows.OfType<MainWindow>().FirstOrDefault();
frmMain.ShowMessageAsync("Erro", ex.Message);
baseGrid.Children.Remove(psbState);
btnSave.IsEnabled = true;
}
System.Media.SystemSounds.Asterisk.Play();
baseGrid.Children.Remove(psbState);
baseGrid.Children.Add(lbState);
ClearContent();
}
Table structure:
CREATE TABLE [dbo].[visitors] (
[Id] INT IDENTITY (1, 1) NOT NULL,
[name] VARCHAR (MAX) NULL,
[document] VARCHAR (50) NULL,
[board] VARCHAR (50) NULL,
[block] INT NULL,
[apartment] INT NULL,
[authorized_from] VARCHAR (MAX) NULL,
[date_entry] DATETIME NULL,
[username] VARCHAR (50) NULL,
[comments] VARCHAR (MAX) NULL,
PRIMARY KEY CLUSTERED ([Id] ASC)
);
I found where the error is, but I do not know how to fix it, error:
Msg 208, Level 16, State 1, Line 4 Invalid object name 'visitors'.
String Connection:
<connectionStrings>
<add name="dbConn" providerName="System.Data.SqlClient"
connectionString="Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\Data\data.mdf;Integrated Security=True"/>