public void ProcessRequest(HttpContext context)
{
MySqlConnection con = new MySqlConnection(ConfigurationManager.ConnectionStrings["ConString"].ConnectionString.ToString());
// Create SQL Command
int adid= int.Parse(context.Request.QueryString["adid"]);
int imgid = int.Parse(context.Request.QueryString["imgid"]);
MySqlCommand cmd = new MySqlCommand();
//cmd.CommandText = "Select i.image_id, i.image_name, i.image_byteImage, i.image_adId from images i,postadverties p where i.image_adId =#ID";
cmd.CommandText = "SELECT image_id,image_byteImage FROM images WHERE image_adId="+ adid + " and image_id="+ imgid;
cmd.CommandType = System.Data.CommandType.Text;
cmd.Connection = con;
//MySqlParameter AdId = new MySqlParameter("#ID", MySqlDbType.Int32);
//MySqlParameter imgid = new MySqlParameter("#imgid", MySqlDbType.Int32);
//AdId.Value =
//imgid.Value =
//cmd.Parameters.Add(AdId);
//cmd.Parameters.Add(imgid);
con.Open();
MySqlDataReader dReader = cmd.ExecuteReader();
if (dReader.Read())
{
byte[] binaryimg = (byte[])dReader["image_byteImage"];
string base64string = "data:image/jpeg;base64," + Convert.ToBase64String(binaryimg);
context.Response.Write(base64string);
context.Response.Flush();
context.Response.End();
}
dReader.Close();
con.Close();
}
Click here to see result
When trying to display images stored in database above result is displayed instead of image.No clue why this issue is coming.Is there any problem while converting it or some else.In another page it works and on some pages it does not.
Related
I've created a form called BookSeat which takes no.of seats as an input and calculate the total fare.
Here's my code:
{
try
{
DB db = new DB();
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT [fare] FROM [dbo].[Train] WHERE name = '" + textBoxName.Text + "' ";
cmd.Connection = db.GetConnection();
db.openConnection();
SqlDataReader dr = cmd.ExecuteReader();
dr.Read();
int d = dr.GetInt32(0);
int noOfSeats = comboBoxNoOfSeats.SelectedIndex;
int totalfare;
totalfare = noOfSeats * d;
textBoxTotalFare.Text = totalfare.ToString();
db.closeConnection();
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}
This shows and error : Invalid attempt to read when no data is present
SqlDataReader has the method called Read which reads all the data inside sqldatareader. But you have to call this function inside while loop.
try
{
DB db = new DB();
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT [fare] FROM [dbo].[Train] WHERE name = '" + textBoxName.Text + "' ";
cmd.Connection = db.GetConnection();
db.openConnection();
SqlDataReader dr = cmd.ExecuteReader();
While(dr.Read())
{
//Get value by using column name;
int d = Convert.ToInt32(dr["columnname"]);
int noOfSeats = comboBoxNoOfSeats.SelectedIndex;
int totalfare;
totalfare = noOfSeats * d;
textBoxTotalFare.Text = totalfare.ToString();
}
dr.Close();
db.closeConnection();
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
I am stuck on collecting 2 column values from a database row.
this method is only working to retrieve one value, not for 2. I need to save values from cells to Different variables then I will use these variables to populate another database.
string connectionString = #"Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=Northwind;Integrated Security=True";
using (var con2 = new SqlConnection(connectionString))
{
try
{
con2.Open();
SqlCommand command = new SqlCommand();
command.Connection = con2;
command.CommandText = string.Format("update Inventory set Quantity= Quantity - {0} WHERE id='"+tbItemid.Text+"'", Convert.ToInt32(tbQuantity.Text));
command.ExecuteNonQuery();
con2.Close();
Data();
DData();
con2.Open();
int x = int.Parse(tbQuantity.Text);
SqlCommand cmd1 = new SqlCommand("SELECT Model from Inventory WHERE id='" + tbItemid.Text + "'", con2);
SqlDataReader modelRdr = null;
modelRdr = cmd1.ExecuteReader();
modelRdr.Read();
modelRdr = cmd1.ExecuteReader();
string model = modelRdr["model"].ToString();
con2.Close();
con.Open();
int y = int.Parse(tbQuantity.Text);
SqlCommand cmd2 = new SqlCommand("SELECT Price from Inventory WHERE id='" + tbItemid.Text + "'", con2);
SqlDataReader pricerdr = null;
pricerdr = cmd2.ExecuteReader();
pricerdr.Read();
int price = int.Parse(pricerdr["Price"].ToString());
SqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "insert into Bill values (" + tbItemid.Text + ",'" +model.ToString()+ "',"+price.ToString()+",'"+tbQuantity.Text+"')";
cmd.ExecuteNonQuery();
con.Close();
Data();
}
catch
{
MessageBox.Show("Enter Catagory and Product ID");
}
}
First thing first you should use Parameterized Queries instead of Concatenations. These kind of queries are prone to SQL Injection. You can read both the columns in one command
SqlCommand cmd1 = new SqlCommand("SELECT Model, Price from Inventory WHERE id='" + tbItemid.Text + "'", con2);
SqlDataReader modelRdr = null;
modelRdr = cmd1.ExecuteReader();
modelRdr.Read();
modelRdr = cmd1.ExecuteReader();
string model = modelRdr["model"].ToString();
int price = int.Parse(modelRdr["Price"].ToString());
The complete code with Parameters would look like
string model=String.Empty;
int price = 0;
string connectionString = #"Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=Northwind;Integrated Security=True";
using (SqlConnection con2 = new SqlConnection(connectionString))
{
try
{
con2.Open();
using(SqlCommand command = new SqlCommand())
{
command.Connection = con2;
command.CommandText = string.Format("update Inventory set Quantity = Quantity - #qty WHERE id=#id";
command.Parameters.AddWithValue("#id", tbItemid.Text);
command.Parameters.AddWithValue("#qty", Convert.ToInt32(tbQuantity.Text)));
command.ExecuteNonQuery();
Data();
DData();
int x = int.Parse(tbQuantity.Text);
using(SqlCommand cmd1 = new SqlCommand("SELECT Model, Price from Inventory WHERE id=#id"))
{
cmd1.Parameters.AddWithValue("#id", tbItemid.Text);
SqlDataReader modelRdr = null;
modelRdr = cmd1.ExecuteReader();
modelRdr.Read();
model = modelRdr["model"].ToString();
price = int.Parse(modelRdr["Price"].ToString());
}
using(SqlCommand cmd = con.CreateCommand())
{
cmd.CommandType = CommandType.Text;
cmd.CommandText = "insert into Bill values (#id,#model,#price,#qty)";.
cmd.Parameters.AddWithValue("#id", tbItemid.Text);
cmd.Parameters.AddWithValue("#model", model);
cmd.Parameters.AddWithValue("#price", price);
cmd.Parameters.AddWithValue("#qty", tbQuantity.Text);
cmd.ExecuteNonQuery();
}
Data();
}
catch
{
MessageBox.Show("Enter Catagory and Product ID");
}
}
}
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);
today, I am trying to use DataRoutines to insert some values into my Access Database. However, it did not work as well as there were no records created. Does anyone know what's wrong with my code?
This is my DataRoutines (dataroutines2) file
public void CreateRecs(string strUserId)
{
OleDbConnection mDB = new OleDbConnection();
mDB.ConnectionString = "Provider = Microsoft.ACE.OLEDB.12.0;Data source="
+ Server.MapPath("~/App_Data/webBase.accdb");
OleDbCommand cmd; OleDbDataReader rdr;
string strSql;
string strOFlag = "F";
// check to see if there is an active order record
strSql = "SELECT eStatus FROM enrolInfo WHERE eUserId = #UserId "
+ "ORDER BY eEnrolNo DESC;";
cmd = new OleDbCommand(strSql, mDB);
cmd.Parameters.Add("#UserId", OleDbType.Char).Value = strUserId;
mDB.Open();
rdr = cmd.ExecuteReader();
Boolean booRows = rdr.HasRows;
if (booRows) //when booRows is true, there are order records for the user
{
rdr.Read();
if ((string)rdr["eStatus"] != "Ordering") //status of an active order is "Ordering"
{
strOFlag = "M"; //"T" means there is a need to create a new Orders record
}
else { strOFlag = "M"; }
mDB.Close();
if (strOFlag == "M")
{
//insert a new order record
string strStatus = "Ordering";
strSql = "INSERT INTO enrolInfo (eUserId, eStatus) VALUES (#UserId, #Status)";
cmd = new OleDbCommand(strSql, mDB);
cmd.Parameters.AddWithValue("#UserId", strUserId);
cmd.Parameters.AddWithValue("#Status", strStatus);
mDB.Open();
cmd.ExecuteNonQuery();
mDB.Close();
}
//get back order No - this order no is needed when the user buys an item
strSql = "SELECT eEnrolNo FROM enrolInfo WHERE eUserId = #UserId "
+ "ORDER BY eEnrolNo DESC;";
cmd = new OleDbCommand(strSql, mDB);
cmd.Parameters.Add("#UserId", OleDbType.Char).Value = strUserId;
mDB.Open();
rdr = cmd.ExecuteReader();
rdr.Read();
Session["tOrderNo"] = rdr["eEnrolNo"]; //store the active order no in the sOrderNo
mDB.Close();
return;
}
}
This is the code that will route the solution to the DataRoutines file in my Register Page
//prepare Session variables for newly register customer
Session["sFlag"] = "M";
Session["tUserId"] = (string)txtUserId.Text;
Session["tName"] = (string)txtName.Text;
Session["tAddress"] = (string)txtAddress.Text;
Session["tTel"] = (string)txtTel.Text;
Session["tEmail"] = (string)txtEmail.Text;
String strUserId = (string)Session["tUserId"];
DataRoutines2 DRObject = new DataRoutines2();
DRObject.CreateRecs(strUserId);
Thanks for your help
I'm trying to make a simple test program that can open MDB files and do 3 basic things
the MDB have 3 fields, all of them are text:
ID
INFO
TEXT
showing data acording to ID = got this working
changing data according to ID = problem
adding new data = problem
the show data works with this code:
con = new OleDbConnection("Provider = Microsoft.Jet.OLEDB.4.0; Data Source = c:\\mdb\\testmdb.mdb");
cmd = new OleDbCommand();
cmd.Connection = con;
cmd.CommandText = "select Info, text from Table1 where ID = '" + int.Parse(textBox1.Text) + "' ";
con.Open(); // open the connection
OleDbDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
textBox2.Text = dr["Info"].ToString();
textBox3.Text = dr["text"].ToString();
}
con.Close();
How do I insert new data in MDB and update data I already have?
Working code
using System;
using ADOX;
using System.Data.OleDb;
using System.Data;
using System.IO;
namespace ConsoleApplication4
{
class Program
{
static void Main(string[] args)
{
CreateMdb("toster_ru.mdb");
string fileNameWithPath = Environment.CurrentDirectory + "\\toster_ru.mdb";
CreateTableInToMdb(fileNameWithPath);
InsertToMdb(fileNameWithPath);
UpdateToMdb(fileNameWithPath);
var myDataTable = new DataTable();
using (var conection = new OleDbConnection("Provider = Microsoft.JET.OLEDB.4.0; Data Source = " + fileNameWithPath))
{
conection.Open();
var query = "Select info From my_table";
var adapter = new OleDbDataAdapter(query, conection);
adapter.Fill(myDataTable);
Console.WriteLine(myDataTable.Rows[0][0].ToString()); //output: toster2.ru
Console.ReadKey();
}
}
static void CreateMdb(string fileNameWithPath)
{
if (File.Exists(fileNameWithPath))
return;
Catalog cat = new Catalog();
string connstr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Jet OLEDB:Engine Type=5";
cat.Create(String.Format(connstr, fileNameWithPath));
cat = null;
}
static void InsertToMdb(string fileNameWithPath)
{
var con = new OleDbConnection("Provider = Microsoft.Jet.OLEDB.4.0; Data Source = " + fileNameWithPath);
var cmd = new OleDbCommand();
cmd.Connection = con;
cmd.CommandText = "insert into my_table (ID, [Info], [text]) values (#ID, #Info, #text);";
cmd.Parameters.AddWithValue("#ID", 1);
cmd.Parameters.AddWithValue("#Info", "toster.ru");
cmd.Parameters.AddWithValue("#text", "blabla");
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
static void UpdateToMdb(string fileNameWithPath)
{
var con = new OleDbConnection("Provider = Microsoft.Jet.OLEDB.4.0; Data Source = " + fileNameWithPath);
var cmd = new OleDbCommand();
cmd.Connection = con;
cmd.CommandText = "UPDATE my_table SET [Info] = ?, [text] = ? WHERE ID = ?;";
cmd.Parameters.AddWithValue("#p1", OleDbType.VarChar).Value = "toster2.ru";
cmd.Parameters.AddWithValue("#p2", OleDbType.VarChar).Value = "blabla2";
cmd.Parameters.AddWithValue("#p3", OleDbType.VarNumeric).Value = 1;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
static void CreateTableInToMdb(string fileNameWithPath)
{
try
{
OleDbConnection myConnection = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0; Data Source=" + fileNameWithPath);
myConnection.Open();
OleDbCommand myCommand = new OleDbCommand();
myCommand.Connection = myConnection;
myCommand.CommandText = "CREATE TABLE my_table([ID] NUMBER, [Info] TEXT, [text] TEXT)";
myCommand.ExecuteNonQuery();
myCommand.Connection.Close();
}
catch { }
}
}
}
Try this for insert:
con = new OleDbConnection("Provider = Microsoft.Jet.OLEDB.4.0; Data Source = c:\\mdb\\testmdb.mdb");
cmd = new OleDbCommand();
cmd.Connection = con;
cmd.CommandText = "insert (ID, Info, text) into Table1 values (#ID, #Info, #text);";
cmd.Parameters.AddWithValue("#ID", textBox1.Text);
cmd.Parameters.AddWithValue("#Info", textBox2.Text);
cmd.Parameters.AddWithValue("#text", textBox3.Text);
con.Open(); // open the connection
//OleDbDataReader dr = cmd.ExecuteNonQuery();
cmd.ExecuteNonQuery();
con.Close();
Try this for update:
con = new OleDbConnection("Provider = Microsoft.Jet.OLEDB.4.0; Data Source = c:\\mdb\\testmdb.mdb");
cmd = new OleDbCommand();
cmd.Connection = con;
cmd.CommandText = "update Table1 set [Info] = #Info, [text] = #text where ID = #ID;";
cmd.Parameters.AddWithValue("#ID", textBox1.Text);
cmd.Parameters.AddWithValue("#Info", textBox2.Text);
cmd.Parameters.AddWithValue("#text", textBox3.Text);
con.Open(); // open the connection
//OleDbDataReader dr = cmd.ExecuteNonQuery();
cmd.ExecuteNonQuery();
con.Close();
For more operations, examine the left panel of this site.