I'm currently trying to develop an application that allows you to track your spending as part of my class. However I run into the error "Invalid object name 'dbo.AccTransactions"
My Windows Form Code:
string command = "Insert INTO dbo.AccTransactions (id, transact_id, payee, dateof, amount, category)"
+ "Values (#id, #transact_id, #payee, #dateof, #amount, #category)";
SqlCommand cmd = new SqlCommand(command, con);
cmd.Parameters.AddWithValue("#id", 1);
cmd.Parameters.AddWithValue("#transact_id", 2);
cmd.Parameters.AddWithValue("#payee", payeeTextBox.Text);
cmd.Parameters.AddWithValue("#dateof", DateTime.Today);
cmd.Parameters.AddWithValue("#amount", Convert.ToDecimal(amountTextBox.Text));
cmd.Parameters.AddWithValue("#category", categoryTextBox.Text);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
My Connection String:
SqlConnection con = new SqlConnection(#"Data Source=IVY\SQLEXPRESS;Initial Catalog=BudgetTracker;Integrated Security=SSPI;Connect Timeout=15;Encrypt=False;TrustServerCertificate=False");
My database has the table "dbo.AccTransactions" and it performs perfectly in SSMS.
Any assistance would be great!
I guess you are missing database name in the connection string.
SqlConnection con = new SqlConnection(#"Data Source=IVY\SQLEXPRESS;Integrated Security=True;Connect Timeout=15;Encrypt=False;TrustServerCertificate=False");
try it by putting the name of your database in the following string.
SqlConnection con = new SqlConnection(#"Data Source=IVY\SQLEXPRESS; Initial Catalog=YOUR_DATABASE_NAME;Integrated Security=True;Connect Timeout=15;Encrypt=False;TrustServerCertificate=False");
Please check that user who is running your program has an access to that table. Most probably you need to set your user as dbo since you accessing the table as dbo.AccTransactions.
Related
I'm trying to insert data into two tables via a WPF app with a button that saves the data, but I keep getting this error and I need some help. I've tried many videos, try to change the tables in the database but I can't get it to work but it works on the Viestit table, but not on Viestihistoria. The error is
System.Data.SqlClient.SqlException: 'Incorrect syntax near '#Viestinlahettaja'
Thank you in advance.
SqlConnection conn = new SqlConnection(#"Data Source=MYCOMPUTER\SQLEXPRESS;Initial Catalog=LomakeDB;User ID=***;Password=***");
conn.Open();
SqlCommand cmd1 = new SqlCommand("INSERT INTO Viestit(ID,Kokonimi,Viesti,Viestin_saaja) values(#ID,#Kokonimi,#Viesti,#Viestin_saaja)", conn);
cmd1.Parameters.AddWithValue("#ID", txtbox_ID.Text);
cmd1.Parameters.AddWithValue("#Kokonimi",txtbox_Nimi.Text);
cmd1.Parameters.AddWithValue("#Viesti", txtbox_Viesti.Text);
cmd1.Parameters.AddWithValue("#Viestin_saaja", txtbox_Viestinvastaanottaja.Text);
cmd1.ExecuteNonQuery();
cmd1.Parameters.Clear();
SqlCommand cmd2 = new SqlCommand("INSERT INTO Viestihistoria(ViestiID,Viesti,Viestin_lahettaja) values(#ViestiID,#Viesti2,#Viestinlahettaja", conn);
cmd2.Parameters.AddWithValue("#ViestiID", txtbox_ID.Text);
cmd2.Parameters.AddWithValue("#Viesti2", txtbox_Viesti.Text);
cmd2.Parameters.AddWithValue("#Viestinlahettaja", txtbox_Nimi.Text);
cmd2.ExecuteNonQuery();
cmd2.Parameters.Clear();
MessageBox.Show("Data lähetetty onnistuneesti!");
conn.Close();
You forgot to add closing ) at the end of this line in sql command text:
The corrected line:
SqlCommand cmd2 = new SqlCommand("INSERT INTO Viestihistoria(ViestiID,Viesti,Viestin_lahettaja) values(#ViestiID,#Viesti2,#Viestinlahettaja)", conn);
I want to create a program for my school, handling marks and certificates.
To save the data I have to use a "local" network shared database-file, because we are using Citrix and there is no possibility to setup an seperate SQL-Server.
I tried it with localdb v11 with the following code:
string connectionString = #"Data Source=(LocalDB)\v11.0; AttachDbFilename=D:\_prog\TestNoten\TestNoten\bin\Debug\Database1.mdf; Integrated Security=True;Connect Timeout=3;";
SqlConnection connection = new SqlConnection(connectionString);
string sql = "INSERT INTO test(name) VALUES('lal')";
SqlCommand cmd = new SqlCommand(sql, connection);
connection.Open();
cmd.ExecuteNonQuery();
connection.Close();
DataTable table = new DataTable();
SqlDataAdapter adp = new SqlDataAdapter("Select * from test", connection);
connection.Open();
adp.Fill(table);
MessageBox.Show(table.Rows[0][1].ToString());
The MessageBox says "lal", but when I restart the program with "lala" instead of "lal", it will show "lala" and not the expected "lal".
So when closing the program, the database won't be saved correctly. I also opened the file over VSs Data Connections, and the testing table is empty.
Is there something I missed?
I'm quite used to using c# with SQL server. I have no idea why a simple statement would fail to insert data. My code is as follows:
query = "INSERT INTO MCDPhoneNumber ([MCDID],[PhoneNumber])" +
"VALUES("+maxid+", '"+tel+"')";
SqlConnection conn = new SqlConnection("Data Source=source; ...");
SqlCommand newCommand = new SqlCommand(query, conn);
int success= myCommand.ExecuteNonQuery();
if (success!= 1)
{
MessageBox.Show("It didn't insert anything:" + query);
}
First of all let me tell that I know that I should use parameters for data and I initially did, but when it failed I tried a simple query and it still fails. For addition I can tell that I have a similar insert just before that one in another table and it works. What's funnier is that when I copy paste query to SQL Server Management Studio it works. It also doesn't report any error in process.
====================== Edit ===============================
If you wish to use old command object (i.e. myCommand) then use following code instead of creating a new command(newCommand)
myCommand.CommandText = query;
myCommand.CommandType = System.Data.CommandType.Text;
And then execute it
you are binding query with newCommand and executing myCommand.
====================== Edit ===============================
SqlCommand newCommand = new SqlCommand(query, conn);
here you have defined newCommand for SQLCOMMAND object
int success= myCommand.ExecuteNonQuery();
and you are accessing it as myCommand
And moreover i think you are not opening connection
First of all, you define your command as newCommand but you executing your myCommand.
You should always use parameterized queries for your sql queries. This kind of string concatenations are open for SQL Injection attacks.
query = "INSERT INTO MCDPhoneNumber (MCDID, PhoneNumber) VALUES(#maxid, #tel)";
using(SqlConnection conn = new SqlConnection("Data Source=source; Initial Catalog=base; Integrated Security = true"))
{
SqlCommand newCommand = new SqlCommand(query, conn);
conn.Open();
newCommand.Parameters.AddWithValue("#maxid", maxid);
newCommand.Parameters.AddWithValue("#tel", tel);
int success= newCommand.ExecuteNonQuery();
if (success != 1)
{
MessageBox.Show("It didn't insert shit:" + query);
}
}
And please be more polite about your error messages :)
When I tried to add a connection it is showing the following error as shown in the attachment. “Unable to open the physical file. Access is Denied” .
When I searched about it, it suggest for adding the SQL Server’s account to the folder. Then, using the following query I found that the account is “LocalSystem”. When I tried to add “LocalSystem” to ACL of the folder, such an account is not available. How do we resolve it and add the connection to DBML?
Note: When I used DataReader with the database name in a C# program, it worked well.
Query Used:
declare #sqlser varchar(20)
EXEC master..xp_regread #rootkey='HKEY_LOCAL_MACHINE',
#key='SYSTEM\CurrentControlSet\Services\MSSQLSERVER',
#value_name='objectname', #value=#sqlser OUTPUT
SELECT convert(varchar(30),#sqlser)
Working C# Program:
SqlDataReader rdr = null;
SqlConnection con = null;
SqlCommand cmd = null;
try
{
// Open connection to the database
string ConnectionString = "server=D088DTRV;integrated security=true; database=BankAccount";
con = new SqlConnection(ConnectionString);
con.Open();
string CommandText = "SELECT * FROM Account";
cmd = new SqlCommand(CommandText);
cmd.Connection = con;
rdr = cmd.ExecuteReader();
while (rdr.Read())
{
string test = rdr["AccountType"].ToString();
}
}
The problem was related to Data Connections.
In the advanced window, when I checked, it was trying for ./SQLExpress. I modified it with ".".
I restarted the machine. I also stopped the SQLExpress in the services.msc
Data Source=.;AttachDbFilename=C:\DevTEST\Databases\LibraryReservationSystem.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True
I'm having immense trouble getting a connection to a .sdf (sql compact edition) database. I can connect initially to extract rows in order to verify a username/password, but when I try to add items to the database, either by a SqlCeConnection/SqlCeCommand command or by trying to add items SqlClient/SqlCommand connection, I have no luck. I get:
A network-related or instance-specific error occurred while establishing
a connection to SQL Server. The server was not found or was not accessible.
Verify that the instance name is correct and that SQL Server is configured to
allow remote connections. (provider: SQL Network Interfaces, error: 26 - Error
Locating Server/Instance Specified)
when using:
private void button1_Click_1(object sender, EventArgs e)
{
System.Data.SqlClient.SqlConnection sqlConnection1 =
new System.Data.SqlClient.SqlConnection("Data Source=C:\\Users\\Tim\\Documents\\Visual Studio 2010\\Projects\\Dispatch POS\\Dispatch POS\\GhsDB.sdf");
System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand();
cmd.CommandType = System.Data.CommandType.Text;
cmd.CommandText = "INSERT [Employee Table] (SSN, FirstName) VALUES ('555-23-4322', 'Tim')";
cmd.Connection = sqlConnection1;
sqlConnection1.Open();
cmd.ExecuteNonQuery();
sqlConnection1.Close();
}
or when I try:
System.Data.SqlClient.SqlConnection sqlConnection1 =
new System.Data.SqlClient.SqlConnection("Data Source=C:\\Users\\Tim\\Documents\\Visual Studio 2010\\Projects\\Dispatch POS\\Dispatch POS\\GhsDB.sdf");
System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand();
cmd.CommandType = System.Data.CommandType.Text;
cmd.CommandText = "INSERT [Employee Table] (SSN, FirstName) VALUES ('555-23-4322', 'Tim')";
cmd.Connection = sqlConnection1;
sqlConnection1.Open();
cmd.ExecuteNonQuery();
sqlConnection1.Close();
Nothing happens, it seems to work until I check the .sdf file and see nothing has been added. I do not have SQL Server CE installed, though I do have 2008 R2 installed (I'm working on someone else's project).
Right now I'm not worried about the security holes, I'm just trying to successfully add a record. Any help would be much appreciated, as I've spent about three or four hours working on something I figure would take about 20 minutes.
Probably you have found the solution by now, but if you use a sdf file, the assembly you should add a reference to System.Data.SqlServerCe and then something like:
SqlCeConnection sqlConnection1= new SqlCeConnection();
sqlConnection1.ConnectionString = "Data Source = C:\\Users\\Tim\\Documents\\Visual Studio 2010\\Projects\\Dispatch POS\\Dispatch POS\\GhsDB.sdf";
System.Data.SqlServerCe.SqlCeCommand cmd = System.Data.SqlServerCe.SqlCeCommand;
cmd.CommandType = System.Data.CommandType.Text;
cmd.CommandText = "INSERT [Employee Table] (SSN, FirstName) VALUES ('555-23-4322', 'Tim')";
cmd.Connection = sqlConnection1;
sqlConnection1.Open();
cmd.ExecuteNonQuery();
sqlConnection1.Close();
you most to use sqlceconnection and sqlcecommand classes. like this :
SqlCeConnection conn = new SqlCeConnection(connectionString);
SqlCeCommand cmd = conn.CreateCommand();
conn.Open();