I keep getting this error:
Invalid object name "CAccounts".
and the code I have is:
System.Threading.Thread thread = new System.Threading.Thread(() =>
{
// Set ConnectionString.
String sConSg =
"CONNSTRING HERE";
using (SqlConnection connection = new SqlConnection(sConSg))
{
try
{
connection.Open();
}
catch (Exception exception)
{
MessageBox.Show(stat.Text = exception.Message);
}
try
{
SqlDataReader slrr = null;
SqlCommand command = new SqlCommand("SELECT ActivationCode FROM CAccounts WHERE ActivationCode = " +
"'" + _activationcode.Text + "'", connection);
slrr = command.ExecuteReader();
while (slrr.Read())
{
if (slrr["ActivationCode"].ToString() == _activationcode.Text)
{
MessageBox.Show(slrr["ActivationCode"].ToString(), "AutoOptimise");
}
else
{
}
}
}
catch (Exception exception)
{
MessageBox.Show(stat.Text = exception.Message);
}
}
});
thread.Start();
Can somebody please shed some light?
The table CAccounts you're referencing in your select clause probably doesn't exist in the database. Check that.
See a list of possibilities here:
http://web.archive.org/web/20150519073601/http://sqlserver2000.databases.aspfaq.com:80/why-do-i-get-object-could-not-be-found-or-invalid-object-name.html
I'd suggest these things:
check which schema the object CAccounts is under. Is it dbo or other? Does the user have permissions on that schema?
login to SQL Server via Management Studio. Use the credentials in the connection string that the code is using. Paste & run the SQL statement above.
use SQL Profiler to capture/verify ensure the SQL statement as it crosses to your SQL Server. Run THAT as an adhoc query against that SQL Server.
are there any funny DNS issues? Hosts files? Does this happen during debugging or on the app server?
is the database server name correct? i.e. localhost versus a named server. Try addressing by the IP address that you expect it to be run at, just for fun, both in your connection string, and via SSMS.
Instead of CAccounts, I had to label it DATABASENAME.dbo.CAccounts.
So it would be something like:
"SELECT * FROM DATABASENAME.db.CAccounts"
This might work:
SqlConnection con = new SqlConnection("Data Source=192.168.1.12;Initial Catalog=Ibrahim;User ID=sa;Password=1412;");
con.Open();
SqlCommand cmd = new SqlCommand("insert into Ibrahim.EVC_Activation_Val (Date,Dealer,Transaction_ID,Invoice_ID,Mobile_Num,Quantity_LE) values('" + DateTimePicker1.Value.ToString("yyyy/mm/dd") + "','" + Txtbx1.Text + "','" + Txtbx2.Text + "','" + Txtbx3.Text + "','" + Txtbx4.Text + "','" + Txtbx5.Text + "')",con);
cmd.ExecuteNonQuery();
MessageBox.Show("Saved");
con.Close();
Related
I have tried MANY suggested solutions from here but nothing seems to work for this problem. I just keep getting this error message when it hits the 'mdr = command.ExecuteReader();' line. Any thoughts please?
try
{
MySqlConnection connection = new MySqlConnection("SERVER=" + server + ";" + "DATABASE=" + database + ";" + "UID=" + uid + ";" + "PASSWORD=" + password + ";");
MySqlCommand command;
MySqlDataReader mdr;
connection.Open();
string ThePID = tbPID.Text;
string TheRound = tbRound.Text;
string CurrentPage = tbCurrentPage.Text;
// SELECT #myvar:= myvalue
string query = "SELECT ImageURL, ProofingText " +
"INTO #ImageURL, #ProofingText " +
"FROM Rounds " +
"WHERE ProjectID = " + ThePID + " " +
"AND CurrentRound = " + TheRound + " " +
"AND Page = " + CurrentPage + ";";
command = new MySqlCommand(query, connection);
mdr = command.ExecuteReader();
mdr.Read();
rtProofing.Text = mdr.GetString("#PRoofingText");
tbURL.Text = mdr.GetString("#ImageURL");
tbImagePage.Text = Path.GetFileName(tbURL.Text);
PageBox.Image = Image.FromFile(tbURL.Text);
connection.Close();
connection.Dispose();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
If you use MySqlConnector, you will get a helpful exception message that explains the problem:
Parameter '#ImageURL' must be defined. To use this as a variable, set 'Allow User Variables=true' in the connection string.
By default, MySQL queries (executed from .NET) can't use user-defined variables. You can relax this limitation by adding Allow User Variables=true to your connection string.
However, this won't fix your underlying problem, which is that this isn't the right way to select data from MySQL.
Firstly, your query is susceptible to SQL injection; you should rewrite it to use parameters as follows:
using (var command = connection.CreateCommand())
{
command.CommandText = #"SELECT ImageURL, ProofingText
FROM Rounds
WHERE ProjectID = #ThePID
AND CurrentRound = #TheRound
AND Page = #CurrentPage;";
commands.Parameters.AddWithValue("#ThePID", ThePID);
commands.Parameters.AddWithValue("#TheRound", TheRound);
commands.Parameters.AddWithValue("#CurrentPage", CurrentPage);
Then, you can retrieve the values with a slight variation on your current code. You must retrieve the values by their column names, which do not have a leading #. You should also check that a row was retrieved by examining the return value of Read():
if (mdr.Read())
{
rtProofing.Text = mdr.GetString("ProofingText");
tbURL.Text = mdr.GetString("ImageURL");
}
Finally, string concatenation is also not the right way to build a connection string. The MySqlConnectionStringBuilder class exists for this purpose; use it.
var builder = new MySqlConnectionStringBuilder
{
Server = server,
Database = database,
UserID = uid,
Password = password,
};
using var connection = new MySqlConnection(csb.ConnectionString);
My SQL statement works fine without the delete statement which is my problem.
I use 2 OleDbCommands to call the seperate queries.
This is my current SQL statement in C#:
string mysql = "Insert Into Completed([Batch number], [Product], [Weight]) VALUES('" + batchNumber + "','" + product + "','" + weight + "')";
string newsql = "DELETE FROM Dryers WHERE [Batch number]='"+batchNumber+"'";
This my latest failed attempt in code:
if (conn.State == ConnectionState.Open)
{
try
{
using (System.Transactions.TransactionScope tScope = new TransactionScope())
{
string batchNumber = txtBatchNumber3.Text.ToString();
string product = txtProduct3.Text.ToString();
string weight = txtWeight3.Text.ToString();
string mysql = "Insert Into Packing([Batch number], [Product], [Weight]) VALUES('" + batchNumber + "','" + product + "','" + weight + "') ";
string newsql = "DELETE * FROM Dryers WHERE [Batch number]='" + batchNumber + "'";
OleDbCommand cmd = new OleDbCommand(mysql, conn);
cmd.ExecuteNonQuery();
OleDbCommand cmd2 = new OleDbCommand(newsql, conn);
cmd2.ExecuteNonQuery();
tScope.Complete();
}
MessageBox.Show("Data saved successfuly...!");
this.Close();
}
catch (Exception ex)
{
MessageBox.Show("Failed due to" + ex.Message);
}
finally
{
conn.Close();
}
}
else
{
MessageBox.Show("Connection Failed");
}
}
}
}
VS2012 gives the following error:
Failed due toData type mismatch in criteria expression.
You can't do this in Access. You have to call two separate SQL strings.
Use two statements but wrap them in a transaction so it's a single unit of work.
BEGIN TRANSACTION
COMMIT
if you wanted to do it in C# then you would wrap your queries in a transaction scope.
using (System.Transactions.TransactionScope tScope = new TransactionScope())
{
//do work here
//if work is completed
tScope.Complete();
//else do nothing the using statement will dispose the scope and rollback your changes.
}
Here is a walkthrough from Microsoft about making the connection against an access database and querying using ADO.NET.
https://msdn.microsoft.com/en-us/library/ms971485.aspx
I am using a Visual Studio 2010 and ASP.net c# language.
I am try to read from excel sheet then insert the information to the Microsoft SQL database, but I found a problem it ignoring the error in the query statement.
for (int i = 0; i < objdatasetdto.Tables[0].Rows.Count; i++)
{
start_time = Convert.ToDateTime(objdatasetdto.Tables[0].Rows[i]["start"].ToString());
end_time = Convert.ToDateTime(objdatasetdto.Tables[0].Rows[i]["end"].ToString());
if (objdatasetdto.Tables[0].Rows[i]["Lecture_day"].ToString().Equals("1"))
{
try
{
query = "Insert into [M].[Lecture]([dd],[start_time],[end_time],[week_no],[sec_no],
[room_no],[building_no]) "+
values('" + Calendar1.SelectedDate.ToShortDateString() + "','" +
start_time.ToShortTimeString() + "','" + end_time.ToShortTimeString() +
"','1','" + objdatasetdto.Tables[0].Rows[i]["section_no"].ToString() + "','"
+ objdatasetdto.Tables[0].Rows[i]["room_no"].ToString() + "','"
+ objdatasetdto.Tables[0].Rows[i]["building_no"].ToString() + "');";
ifexist = new SqlCommand(query, cnn);
}
catch (Exception ex)
{
Response.Write(ex);
}
}//end if
}// end for loop
I wrote [dd] column instead of [date] to test if it detect the error or not. but it just ignores them completely.
How can I solve this problem.
You don't appear to be executing the SqlCommand. Try adding:
ifexist.ExecuteScalar();
where you have executed the query?
You have not written anything in one of the following
ifexist.ExecuteScalar();
ifexist.ExecuteNonQuery();
If you don't execute you query how the query will be compiled and how will you expect an error.
This is my code I think I am doing right so far but I really dunno what is the problem.
I am making a register form with txtbox for username and password I encrypt the password with MD5, I tried deleting the MD5 encryption thinking that it might be the prtoblem but still when I deleted it the problem is still occur.
ApareceCrudLib a = new ApareceCrudLib("localhost", "root", "", "cashieringdb");
string query = "INSERT INTO register (username,password) " +
"VALUES(" +
"'" + txtUser.Text + "'," +
"MD5('" + txtPass.Text +"')";
a.mysqlInsert(query);
MessageBox.Show("Account has been registered!");
this.Close();
This is the code for my class ApareceCrudLib for mysqlInsert
public void mysqlInsert(string query)
{
try
{
if (this.Open())
{
MySqlCommand cmd = new MySqlCommand(query, conn);
cmd.ExecuteNonQuery();
this.Close();
System.Windows.Forms.MessageBox.Show("Record Inserted!");
}
}
catch { this.Close(); System.Windows.Forms.MessageBox.Show("INSERT Record Error!"); }
return;
}
as you can see I catch the error with dialog box so basically if it will fail to insert or connect to database the message box shows "INSERT Record Error!". By the way there is no error in visual studio only in inserting to database.
I think the error somewhere in the code for inserting database string query = "INSERT
INTO register (username,password) " +
"VALUES(" +
"'" + txtUser.Text + "'," +
"MD5('" + txtPass.Text +"')";
maybe a comma a semi-colon a period I am clueless.
Hi!rhughes here is the image of the error!
you must add a ")" to your string query.
string query = "INSERT INTO register (username,password) " +
"VALUES(" +
"'" + txtUser.Text + "'," +
"MD5('" + txtPass.Text +"'))";
^ HERE
The SQL is not correct. You have two opening "(" and only one closing.
In order to see the actual error, try this:
try
{
if (this.Open())
{
MySqlCommand cmd = new MySqlCommand(query, conn);
cmd.ExecuteNonQuery();
this.Close();
System.Windows.Forms.MessageBox.Show("Record Inserted!");
}
}
catch(Exception ex)
{
this.Close();
System.Windows.Forms.MessageBox.Show(String.Format("INSERT Record Error! {0}", ex.Message));
}
How do you insert into a table in a .sdf database?
I've tried the following:
string connection = #"Data Source=|DataDirectory|\InvoiceDatabase.sdf";
SqlCeConnection cn = new SqlCeConnection(connection);
try
{
cn.Open();
}
catch (SqlCeException ex)
{
MessageBox.Show("Connection failed");
MessageBox.Show(ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
Application.ExitThread();
}
string clientName = txt_ClientName.Text;
string address = txt_ClientAddress.Text;
string postcode = txt_postcode.Text;
string telNo = txt_TelNo.Text;
string sqlquery = ("INSERT INTO Client (Name,Address,Postcode,Telephone_Number)Values(" + clientName + "','" + address + "','" + postcode + "','" + telNo + ")");
SqlCeCommand cmd = new SqlCeCommand(sqlquery, cn);
try {
int affectedRows = cmd.ExecuteNonQuery();
if (affectedRows > 0)
{
txt_ClientAddress.Text = "";
txt_ClientName.Text = "";
txt_postcode.Text = "";
txt_TelNo.Text = "";
MessageBox.Show("Client: " + clientName + " added to database. WOoo");
}
}
catch(Exception){
MessageBox.Show("Insert Failed.");
}
But it doesn't seem to matter what i do it just shows "Insert Failed".
Thanks in advance.
You forgot opening quotation mark on the first value.
Values(" + clientName + "','"
change to:
Values('" + clientName + "','"
But this is generally a bad way to build query. Use parametrized query instead.
See: http://msdn.microsoft.com/en-us/library/system.data.sqlserverce.sqlcecommand.parameters(v=vs.80).aspx
catch(Exception ex)
{
MessageBox.Show(ex);
}
Will give you more info on error.
It is the same old story. When you build a sql command concatenating string these kinds of errors abund. And the simple syntax problem is not the worst. The Sql Injection is the most dangerous one.
Please build your query in this way
string sqlquery = ("INSERT INTO Client (Name,Address,Postcode,Telephone_Number)" +
"Values(#client,#address, #postcode, #tel)";
SqlCeCommand cmd = new SqlCeCommand(sqlquery, cn);
cmd.Parameters.AddWithValue("#client", clientName);
cmd.Parameters.AddWithValue("#address", address);
cmd.Parameters.AddWithValue("#postcode", postcode);
cmd.Parameters.AddWithValue("#tel", telNo);
cmd.ExecuteNonQuery();
As others have already said your syntax error is caused by omitting the initial single quote. But you could have other errors. For example, what about a client called O'Hara?. Now you have a single quote inside the clientname and this wreak havoc your string concatenation.
Instead a parameter will be accurately parsed and every problematic character found will be treated appropriately (in this case doubling the single quote)
Your SQL statement is incorrect.
string sqlquery = ("INSERT INTO Client (Name,Address,Postcode,Telephone_Number)Values('" + clientName + "','" + address + "','" + postcode + "','" + telNo + "')");
Take this. You forgot the ' at the beginning and the end of the values
To insert data into Sql, data type should be considered. If you insert a string value (varchar) you have to surround it by single quotation, like '"+full_Name+"', but integer type doesn't need this. example
string myQuery = "INSERT INTO Persons (phone, fullname) VALUES ("+telNo+",'"+full_Name+"')";
where full name is string variable and phone number is only number.