After fighting with this for some time I tried even this very degenerate example (the correct one should be "SHOW VARIABLES like 'max_allowed_packet'") and it still fails:
String CommandText = "Show variables;";
MySqlCommand Command = new MySqlCommand(CommandText, Connection);
using (MySqlDataReader Reader = Command.ExecuteReader())
while (Reader.Read())
return (int)Reader["Value"];
^c^ving the command text into the workbench produces the expected result for every query I have tried. No matter what syntax I use for the show variables I get "Enumeration yielded no results" in the reader and of course it crashes trying to cast that to an integer. Immediately before hitting this code there was a Change Database command done with the connection so it must be open.
I can't think of anything that could be wrong here that would allow the query to execute at all (it does figure out the field count should be 2 so it must have talked to the database) and yet not give me any results.
The suggested question certainly looks like mine but I already tried that case:
Select * from information_schema.global_variables where variable_name like 'max_allowed_packet'
and got the same result--nothing. As before, copying the text out of the debugger and pasting it in the workbench yields the right result. How can this one situation produce no results without producing a total failure?
SHOW GLOBAL VARIABLES; should work with 5.6.17 or greater versions
or SHOW LOCAL VARIABLES if you are looking for session variables.
Related
I've searched all through the internet, and there is no way that I have found to do what I'm asking for. Here's my code:
using (MySqlConnection connection = new MySqlConnection(verbindung))
{
connection.Open();
string query = $#"show tables like '%{tbSearch.Text}%'";
MySqlCommand command = new MySqlCommand(query, connection);
using (MySqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
listR.Add(reader.GetString(0));
btnAccount.Text = listR[0];
btnAccount2.Text = listR[1];
}
}
}
What I expect:
To get two strings if there is more than one Table available.
I add in the values separately using the code below, considering when I tried using an AutoCompleteMenu it was able to separate each string e.g. PrX#0000 and PxL#0000 are not in the same line or value.
Display the values on buttons (I can do this part myself, I just gotta know how to separate values from the Query into separate strings.
What I got:
An error at: btnAccount2.Text = listR1; with the error being:
System.ArgumentOutOfRangeException: 'Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index'
I guess that's because of the string not being separated into 2 by itself
I tried pretty much everything and searched all around the internet, and was still not able to find any way to do this.
Here's the data I'm trying to get from the reader:
Data
Here's what I get when I show the data of GetString(0) in a MessageBox.
The first table
The second table
I get 2 MessageBoxes when I do MessageBox.Show(reader.GetString(0));
One normally after I type the first letter of the table in the Textbox, the second after I close the first MessageBox.
You will "get two strings if there is more than one Table available." The loop (around reader.Read()) will provide a separate string for each row in the dataset, i.e., each table in your database.
You need to move the access of the two strings outside the loop. The first time the loop runs, you only have one string, so you can't access both of them yet.
listR.Clear();
using (MySqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
listR.Add(reader.GetString(0));
}
btnAccount.Text = listR[0];
btnAccount2.Text = listR[1];
Note that this code will still crash if there are fewer than two tables, it will ignore any tables past the first two, and it will pick the first two tables in arbitrary order (because there's no ORDER BY in your query).
I have a problem in my program that's supposed to store projects given by the user in a database. I'm stuck on the edit project button. After entering new values in the program and hitting the button to save the values everything runs successfully with no errors. The messagebox that says "project edited" appears, I hit ok but the database stays the same. There is no error in the code, the SQL code that gets sent to update the database values is also correct but it doesn't work. Can anyone help with this because I am lost.
Here is the method that creates and executes the SQL code to update the database.
enter image description here
Wow man that code is wrong in so many ways according to code standards and principles most popular :) but that is not what the question is about directly, though getting you past lost we have to start at the basic tbh:
Suggestions
when you catch that exception if it comes, show that in a messagebox also you can even add an error icon as part of the .Show command, it's build in.
Move the connection.Close to the finally block instead of having it replicated
Consider making an SQL procedure instead and just parse the parameter into that, this code is prone to sql injection that you pose
Consider not making the procedure and familiarize Yourself with entity framework, it's going to make your life so much easier
do not concatenate like that, use interpolation or string.Combine or you'll be copying stuff all around on the stack, for each + a new copy one and two into third, it is super inefficient
When You write the code works and the sql is correct, consider that the outcome is not the desired and therefore it doesn't technically ;) the best and the worst about computers, is that they do what you ask.
Don't write Your DAL code in the form at all
Consider checking your parameters for default values
You do not have data to say 'project was updated' only 'values were saved', you do not check the old values in the code
Still besides that I do not see why what you wrote wouldn't work, provided the resulting sql is valid in what db you use, but i suppose if you do some of these things the error will present itself
I don't think it's a connection problem because I have a function that updates only the finishdate of the project and that works completely fine.
Here is the function:
public static MySqlCommand FinishProject(int projID, string finishdate) {
try {
if (connection != null) {
connection.Open();
cmd = connection.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#value", projID);
cmd.Parameters.AddWithValue("#finishdate", finishdate);
cmd.CommandText = "UPDATE `b1c`.`projects` SET `finishdate` = (#finishdate) WHERE (`projectid` = (#value));";
int i = cmd.ExecuteNonQuery();
connection.Close();
if (i != 0) {
MessageBox.Show("Project finalized.");
i = 0;
}
}
} catch (Exception ex) {
MessageBox.Show("Catch");
connection.Close();
}
return cmd;
}
You can see it's basically the same the only difference are the values.
So it shouldn't be a connection thing because this one works fine I think.
I also don't think it's a problem in the SQL database because all the problems
I've had up until now that had anything to do with the database have shown as errors in visual studio.
If anyone can help I will provide screenshots of anything you need and thank you all once again for trying to help.
Here is the screenshot of the function I've pasted previously so it's easier to look at.
finishprojectfunction
I have a long set of SQL scripts. They are all update statements. It's for an access database. I want to validate the script before I run it. Firstly, I'd like to make sure that the query can be parsed. I.e. that the SQL is at least syntactically correct. Secondly, I'd like to make sure that the query is valid in terms of database structure - i.e. there are no missing columns or the columns are of the wrong type etc. But, I don't want the query to be actually executed. The aim of this is to do a quick validation before the process kicks off because the process takes several hours and one syntactical error can waste a day of someone's time.
I will probably write the tool in C# with .net but if there's a pre-built tool that would be even better. I will probably use the Access API. In SQL Server this is very straight forward. You can just validate the query in SQL Server management studio before running it. It will give you a good indication of whether the SQL will complete or not.
How would I go about doing this?
Edit: an answer below solves the issue of checking syntax. However, I'd still like to be able to validate the semantic content of the query is OK. However, I think this might be impossible in Access without actually running the query. Please tell me I'm wrong.
I'm not 100% sure if Access works the same way as a traditional database, but with a mainstream RDMBS, there are actually three distinct steps that happen when you run a query:
Prepare
Execute
Fetch
Most are oblivious to the distinction because they just hit "run" and see results come back.
It's the "Execute" that actually compiles the statement before going off and pulling data.
When you use ADO, you can actually see the three events as three separate calls to the database. What this means is you can trap the execute step to see if it fails, and if it succeeds, there is nothing requiring you to actually get the results.
OleDbConnection conn = new OleDbConnection();
conn.ConnectionString = String.Format("{0}{1}",
#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=", #"c:\Access\MyDb.accdb");
conn.Open();
bool valid;
using (OleDbCommand cmd = new OleDbCommand("select [Bad Field] from [Table]", conn))
{
try
{
OleDbDataReader reader = cmd.ExecuteReader();
valid = true;
reader.Close(); // Did not ever call reader.Read()
}
catch (Exception ex)
{
valid = false;
}
}
And now valid indicates whether or not the statement compiled.
If you want to get really fancy, you can parse the exception results to find out why the command failed.
Access supports transactions on its Connection object. Try to execute your SQL statement inside a transaction and always call Rollback. Wrap the whole attempt in a Try/Catch block to assess whether the statement executed successfully or not.
I've inherited an application with a lot of ADO work in it, but the insert/update helper method that was written returns void. We've also been experiencing a lot of issues with data updates/inserts not actually happening. My goal is to update all of them to check rows affected and depending on the results, act accordingly, but for the time being of finding what may be causing the issue, I wanted to log SQL statements that are called against the server and the number of rows affected by the statement.
This is the statement I'm attempting:
SqlCommand com = new SqlCommand(String.Format("'INSERT INTO
SqlUpdateInsertHistory(Statement, AffectedRows) VALUES (''{0}'', {1});'",
statement.Replace("'", "''"), rows), con);
but it seems to constantly break somewhere in the sql that is being passed in (some cases on single quotes, but I imagine there are other characters that could cause it as well.
Is there a safe way to prep a statement string to be inserted?
I just can't rightly propose a solution to this question without totally modifying what you're doing. You're currently wide open to SQL Injection. Even if this is a local application, practice how you want to play.
using (SqlCommand com = new SqlCommand("INSERT INTO SqlUpdateInsertHistory(Statement, AffectedRows) VALUES (#Statement, #AffectedRows)", con))
{
com.Parameters.AddWithValue("#Statement", statement);
com.Parameters.AddWithValue("#AffectedRows", rows);
com.ExecuteNonQuery();
}
Have you tried SQL Server Profiler? It's already been written and logs queries, etc.
Someone else tried this and got a lot of decent answers here.
The following post relates to the System.Data.SQLite data provider by phxsoftware (http://sqlite.phxsoftware.com)
I have a question (and possibly a problem) with DbDataReader’s Read method and/or Visual Studio 2008. In many examples I see things like the following (and I know this code doesn't make a lot of sense ... but it serves a purpose):
DbDataReader reader = null;
Long ltemp = 0;
lock (m_ClassLock)
{
DbCommand cmd = dbCnn.CreateCommand();
cmd.CommandText = “SELECT col1 FROM table1”;
reader = cmd.ExecuteReader();
if (null != reader)
{
while (reader.Read())
{
ltemp += (long)reader[0];
}
}
reader.Close();
First question - What I dont understand from this example is am I missing data the first time through the while loop by calling reader.Read() upfront? For instance, if the reader has values (3,5,7,9) the returned reader from cmd.ExecuteReader() should be pointing at 3 initially, correct? reader.Read() would then move to 5, 7, and 9 on subsequent invocations within the while loop. But, because reader.Read() is invoked before the first "ltemp += ..." line am I skipping past the first result (3)?
Second question - (and I'm starting to think this might be a bug in VS) If I step through this set of code in the debugger when I stop at a breakpoint on the "if (null != ..." line I can clearly see mu mousing over and drilling down in the popup that reader has multiple row data values assigned to it. However, if I close that popup information, and then try to bring it back up, when I drill down I now see the line "Enumeration yielded no results" where there was clearly data before.
Can anyone explain this behavior?
Think about it like this after you run ExecuteReader the set is on row -1. You need to execute Read to get to row 0.
IDataReader is a forward only structure, you can only iterate through it once, the debugger is iterating through it.
General questions:
Why the lock?
Why the null check for reader - I am not aware of any issues where ExecuteReader return null after a select.
Why not "SELECT SUM(col1) from table1
Why are you not following the dispose pattern?