I'm trying to populate two ArrayLists (listOfAnswers and listOfAnswerIDs) with fields from a database ('answer' and 'answer_id').
The following code seems to work perfectly fine when question_id=1 in the string cmdText. However, if I change this to 2 or 3, the ArrayLists remain empty and I don't know why. Any ideas?
I think it's to do with the string cmdGetAnswersQuery as "SELECT * FROM answers WHERE question_id=2" works...
string connStr = ConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString;
MySqlConnection conn = new MySqlConnection(connStr);
MySqlDataReader reader;
ArrayList listOfAnswerIDs = new ArrayList();
ArrayList listOfAnswers = new ArrayList();
try
{
conn.Open();
string cmdText = "SELECT * FROM questions_t WHERE question_id=2";
MySqlCommand cmd = new MySqlCommand(cmdText, conn);
cmd.Parameters.Add("#ModuleID", MySqlDbType.Int32);
cmd.Parameters["#ModuleID"].Value = ddlModules.SelectedValue;
reader = cmd.ExecuteReader();
if (reader.Read())
{
lblQuestion.Text = reader["question"].ToString();
ViewState["QuestionID"] = reader["question_id"].ToString();
ViewState["AnswerID"] = reader["correct_answer_id"].ToString();
reader.Close();
string cmdGetAnswersQuery = "SELECT * FROM answers WHERE question_id=#QuestionID";
MySqlCommand cmdGetAnswers = new MySqlCommand(cmdGetAnswersQuery, conn);
cmdGetAnswers.Parameters.Add("#QuestionID", MySqlDbType.Int32);
cmdGetAnswers.Parameters["#QuestionID"].Value = ViewState["AnswerID"];
reader = cmdGetAnswers.ExecuteReader();
while (reader.Read())
{
listOfAnswerIDs.Add(reader["answer_id"].ToString());
listOfAnswers.Add(reader["answer"].ToString());
}
reader.Close();
populateAnswers(listOfAnswers, listOfAnswerIDs);
}
else
{
reader.Close();
lblError.Text = "(no questions found)";
}
}
catch
{
lblError.Text = "Database connection error - failed to insert record.";
}
finally
{
conn.Close();
}
The actual database contents are shown here:
http://i.imgur.com/3S4lV60.png
http://i.imgur.com/8A913xF.png
I can't say for sure that this is the problem, but the first thing I'd look at is this line of code:
cmdGetAnswers.Parameters["#QuestionID"].Value = ViewState["AnswerID"];
I suspect you want that to be ViewState["QuestionID"].
Related
I´m having some issue inserting a new record to this table.
Though can't seem to find the real issue within my code.
try
{
conn = new MySqlConnection(cs.ConnString);
conn.Open();
cmd = new MySqlCommand();
cmd.Connection = conn;
cmd.CommandText = "insert into Depense_Vehicule (Code,Date,Responsable,Source_Cr,Numero_Plaque_Dt,Possession,Chauffeur,Categorie,Type,Libelle,Montant_$,Montant_FC,Taux_Echange,Total_$,Status)" +
"VALUES (#d1,#d2,#d3,#d4,#d5,#d6,#d7,#d8,#d9,#d10,#d11,#d12,#13,#14,#15)";
cmd.Parameters.AddWithValue("d1", Code_ADV_txt.Text);
cmd.Parameters.AddWithValue("d2", Date_ADVe_dt.Text);
cmd.Parameters.AddWithValue("d3", Responsable_ADV_txt.Text);
cmd.Parameters.AddWithValue("d4", Source_ADV_cb.Text);
cmd.Parameters.AddWithValue("d5", Numero_Plaque_ADV_txt.Text);
cmd.Parameters.AddWithValue("d6", Possesion_ADV_txt.Text);
cmd.Parameters.AddWithValue("d7", Chauffeur_ADV_cb.Text);
cmd.Parameters.AddWithValue("d8", Categorie_ADV_cb.Text);
cmd.Parameters.AddWithValue("d9", Type_Payment_ADV_cb.Text);
cmd.Parameters.AddWithValue("d10", Libelle_ADV_txt.Text);
cmd.Parameters.AddWithValue("d11", MontantDollars_ADV_txt.Text);
cmd.Parameters.AddWithValue("d12", MontantFranc_ADV_txt.Text);
cmd.Parameters.AddWithValue("d13", TauxEchange_ADV_txt.Text);
cmd.Parameters.AddWithValue("d14", TotalDollars_ADV_txt.Text);
cmd.Parameters.AddWithValue("d15", Status_ADV_cb.Text);
MySqlDataReader myReader;
myReader = cmd.ExecuteReader();
conn.Close();
MessageBox.Show("Record Ajouter");
Source_ADV_cb.SelectedIndex = -1;
Chauffeur_ADV_cb.SelectedIndex = -1;
Numero_Plaque_ADV_txt.Text = "";
Possesion_ADV_txt.Text = "";
Categorie_ADV_cb.SelectedIndex = -1;
Type_Payment_ADV_cb.SelectedIndex = -1;
MontantDollars_ADV_txt.Text = "";
MontantFranc_ADV_txt.Text = "";
TotalDollars_ADV_txt.Text = "";
Status_ADV_cb.SelectedIndex = -1;
Libelle_ADV_txt.Text = "";
}
catch (Exception ex)
{
MessageBox.Show(ex.StackTrace);
}
finally
{
conn.Close();
}
I think you must use cmd.ExecuteNonQuery instead of cmd.ExecuteReader().
ExecuteReader is for run SQL SELECT command.
I hope this answer is useful for you.
I am trying to display pictures from my SQLSEVER database on my website. My users have a picture field with a picture datatype. If the picture column is null, then I want the picture displayed to be a egg.jpg, but right now for every person their picture is egg.jpg, even if they have a picture in the database. Here is my method.
public string getImageUrl()
{
System.Data.SqlClient.SqlConnection sc = new System.Data.SqlClient.SqlConnection();
sc.ConnectionString = "Server =MRCOMPUTER2\\SQLEXPRESS; Database = WBL;Trusted_Connection=Yes;";
sc.Open();
System.Data.SqlClient.SqlCommand insert = new System.Data.SqlClient.SqlCommand();
insert.Connection = sc;
insert.CommandText = "SELECT profilePicture from SystemUser";
insert.ExecuteNonQuery();
SqlDataReader reader = insert.ExecuteReader();
string url = "";
while (reader.Read())
{
if ( !DBNull.Value.Equals(reader[0]))
{
url = "data:Image / png; base64," + Convert.ToBase64String((byte[])reader[0]);
}
else {
url = "images/egg.jpg";
}
}
return url;
}
Your code returns the image for the last user in your table.
Here:
insert.CommandText = "SELECT profilePicture from SystemUser";
you select all users from the table (not just the one you currently show). Then:
while (reader.Read())
{
...
url = ...
...
}
you re-assign url inside every iteration of your while loop. This is semantically equivalent to:
url = ... /* The value determined from the last record of the reader. */
Thus, all your users show the same image - the one of the last user in your table.
You SELECT statement is attached into a ExecuteNonQuery?
Take it off.
Just perform the READER statement...
Try this:
static void Main(string[] args)
{
string connectionString = "Server=.;Database=AA;Trusted_Connection=True;";
/*
CREATE TABLE [dbo].[SystemUser]
(
[ProfilePicture] [varbinary](max) NULL
)
*/
using (SqlConnection connection = new SqlConnection(connectionString))
{
string sql = #"
INSERT [AA].[dbo].[SystemUser] ([ProfilePicture]) VALUES (#ProfilePicture);
INSERT [AA].[dbo].[SystemUser] ([ProfilePicture]) VALUES (NULL);
";
SqlCommand command = new SqlCommand();
command.Connection = connection;
command.CommandText = sql;
command.CommandType = CommandType.Text;
byte[] bytes = File.ReadAllBytes(#"1.jpg");
command.Parameters.AddWithValue("#ProfilePicture", bytes);
connection.Open();
command.ExecuteNonQuery();
}
DataSet ds = new DataSet();
using (SqlConnection connection = new SqlConnection(connectionString))
{
string sql = #"
SELECT TOP 1000 [ProfilePicture] FROM [AA].[dbo].[SystemUser];
";
SqlCommand command = new SqlCommand();
command.Connection = connection;
command.CommandText = sql;
command.CommandType = CommandType.Text;
connection.Open();
SqlDataAdapter da = new SqlDataAdapter(command);
da.Fill(ds);
}
var rows = ds.Tables[0].Rows.Cast<DataRow>();
foreach (DataRow row in rows)
{
byte[] bytes = row.Field<byte[]>(0);
if (bytes != null)
{
string fileName = Guid.NewGuid().ToString("N") + ".jpg";
File.WriteAllBytes(fileName, bytes);
}
}
}
Can you try using the name of the column such as
var Val = (String)reader["column name"];
Also, try something like this to test:
while (reader.Read())
{
var testVal = reader.GetString(0);
Var testVal2 = reader.GetString(1);
i got a database table that contains:
Name,X,Y,Z
here's the part i'm selecting some values from the database :
MySqlConnection myConn = new MySqlConnection(myConnection);
MySqlCommand command = myConn.CreateCommand();
command.CommandText = "SELECT Name , X, Y, Z FROM gestures ";
MySqlDataReader myReader;
try
{
myConn.Open();
myReader = command.ExecuteReader();
while (myReader.Read())
{
FromDB.Name = myReader[0].ToString();
MPoint asdd = new MPoint((double)myReader[1], (double)myReader[2], (double)myReader[3]);
FromDB.FDB.Add(asdd);
}
files.Add(FromDB);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
myConn.Close();
what i'm asking for is how to select distinct name instead of selecting the repeated names and selecting all the X,Y,Z points even the repeated ones
i hope i clarified my question
To select all records on a unique column from a MySQL database using C#:
using MySql.Data.MySqlClient;
...
var connectionString = "<insert connection string here>";
using (var connection = new MySqlConnection(connectionString))
{
connection.Open();
var query = "select * from gestures group by name";
var command = new MySqlCommand(query, connection);
using (var reader = command.ExecuteReader())
{
while (reader.Read())
{
var name = reader.GetString(0);
var pointX = reader.GetInt32(1);
var pointY = reader.GetInt32(2);
var pointZ = reader.GetInt32(3);
Console.WriteLine($"{name}: {x},{y},{z}");
}
}
}
Edit: Link to MySQL C# documentation.
I have the following code:
string myConnection = "server=localhost;database=test;uid=test;password=test";
string query = "SELECT label_type, label, quantity FROM system_printserver WHERE print=0";
try
{
MySqlConnection myConn = new MySqlConnection(myConnection);
myConn.Open();
MySqlCommand command = new MySqlCommand(query, myConn);
MySqlDataAdapter adapter = new MySqlDataAdapter(command);
DataTable data = new DataTable();
adapter.Fill(data);
dataGridView1.DataSource = data;
printDocument1.PrintPage += new PrintPageEventHandler(printDocument1_PrintPage);
MySqlDataReader myReader;
myReader = command.ExecuteReader();
while (myReader.Read()) {
orderNumber = myReader.GetString(1);
myReader.Close();
string queryOrder = "SELECT id_order, id_carrier FROM ps_orders WHERE id_order=28329";
MySqlCommand commandOrder = new MySqlCommand(queryOrder, myConn);
MySqlDataReader myReaderOrder;
myReaderOrder = commandOrder.ExecuteReader();
idCarrier = myReaderOrder.GetString(1);
printDocument1.Print();
}
I have a problem because the second query string queryOrder doesn't work. The query is Ok but variable "idCarrier" doesn't accept any value.
I don't believe you can attach another reader to a connection, when one is already open and processing records. You must retrieve all your records first, i.e. ToList() or Dataset, or use a secondary connection for the second reader.
To make your life easier, consider using Dapper or Linq2Db, two awesome micro-ORMs.
Try it like this:
using(var connection = new MySqlConnection("server=localhost;database=test;uid=test;password=test") {
connection.Open();
int orderNumber = 0;
using (var command = connection.CreateCommand()) {
command.CommandText = #"SELECT label_type, label, quantity FROM system_printserver WHERE print=0";
DataTable data = new DataTable();
adapter.Fill(data);
dataGridView1.DataSource = data;
var reader = command.ExecuteReader();
printDocument1.PrintPage += new PrintPageEventHandler(printDocument1_PrintPage);
if(reader.Read()) {
orderNumber = Convert.ToInt32(reader.GetString(1));
}
}
using(var command = connection.CreateCommand()) {
command.CommandText = string.format(#"SELECT id_order, id_carrier FROM ps_orders WHERE id_order={0}",orderNumber);
var reader = command.ExecuteReader();
if(reader.Read()){
printDocument1.Print();
return reader.GetString(1);
}
}
}
public Users GetUserById(string _id)
{
MySqlConnection conn = new MySqlConnection(connstr);
conn.Open();
string sql = ("select * from Books where id = " + _id);
MySqlCommand cmd = new MySqlCommand(sql, conn);
MySqlDataReader reader = cmd.ExecuteReader();
Users obj = new Users();
if (reader.Read())
{
obj.id = Convert.ToInt32(reader[0]);
obj.UserName = reader[1].ToString();
}
reader.Close();
conn.Close();
return obj;
}
I am puuling the info in Json Format but
Out Put for this is: {"UserName":"John","id":1}
Expected Out put is: [{"UserName":"John","id":1}]
I am missing the Square braces for the record
Whats the problem with my code?
Your expected output i.e. [{"UserName":"John","id":1}]
represents the List of Users object.
So if you want such output should return from your function then you just need to return a List of user from your function.
But as your function name GetUserById, I think it should return single user( So I don't know why are trying to return an array of users from this)
But anyway you can get the expected output in this way
public List<Users> GetUserById(string _id)
{
MySqlConnection conn = new MySqlConnection(connstr);
conn.Open();
string sql = ("select * from Books where id = " + _id);
MySqlCommand cmd = new MySqlCommand(sql, conn);
MySqlDataReader reader = cmd.ExecuteReader();
List<Users> users=new List<Users>();
Users obj = new Users();
if (reader.Read())
{
obj.id = Convert.ToInt32(reader[0]);
obj.UserName = reader[1].ToString();
users.Add(obj);
}
reader.Close();
conn.Close();
return users;
}
Now whenever this users convert into json format, it will return the expected output.