I am developing a basic C# application that will read folder names and insert them into a DB.
However it keeps throwing
System.Data.SqlClient.SqlException (0x80131904): Invalid object name 'CDA'.
(CDA is name of my database)
This is the code in question
static void InsertSql(Guid folderGuid, string folderName)
{
try
{
// Build connection string
SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder
{
DataSource = "WIN10-LAP-HJP",
UserID = "sa",
Password = "Mypassword123",
InitialCatalog = "master"
};
// Connect to SQL
Console.Write("Connecting to SQL Server ... ");
using (SqlConnection connection = new SqlConnection(builder.ConnectionString))
{
Console.WriteLine("Done.");
string query = "INSERT INTO CDA ( FolderName) VALUES (@FolderName )";
using (SqlCommand command = new SqlCommand(query, connection))
{
command.Parameters.Add("@FolderID", SqlDbType.UniqueIdentifier).Value = folderGuid;
command.Parameters.Add("@FolderName", SqlDbType.NVarChar ).Value = folderName;
connection.Open();
var result = command.ExecuteNonQuery();
// Check Error
if (result < 0)
Console.WriteLine("Error inserting data into Database!");
}
}
}
catch (SqlException e)
{
Console.WriteLine(e.ToString());
}
}
This is an image of my mssql
My database connection string seems to work
as I do get
connecting to sql server...Done
And then it throws the error.
You are connecting the entire database and does not specify which table in the database it should use. When considering the information you provided.
Correct the name of your database in the SqlConnectionStringBuilder from master
to CDA
:
InitialCatalog = "CDA"
Change your insert statement so that it reflects the actual table where you want to save your data:
string query = "INSERT INTO dbo.MyTableTableNameGoesHere ( FolderName) VALUES (@FolderName )";
As you said CDA is the database name so the below code should be changed with the table name.
INSERT INTO CDA (FolderName) VALUES (@FolderName) //Change CDA to table name.
It should be
INSERT INTO [CDA].[dbo].[FolderInfo] VALUES (@FolderName)
Apart from the above two correction you need to change the connection string.
InitialCatalog = "master"
should be
InitialCatalog = "CDA"
User contributions licensed under CC BY-SA 3.0