Provider & query - c#

I want to create a C # application that can create and populate a DataTable.
Here is my code:
public DataTable GetData(string query)
{
DbProviderFactory factory = DbProviderFactories.GetFactory("System.Data.OracleClient");
using (DbConnection conn = factory.CreateConnection())
{
try
{
DbConnectionStringBuilder csb = factory.CreateConnectionStringBuilder();
csb["Data Source"] = #"";
csb["User Id"] = #"";
csb["Password"] = #"";
conn.ConnectionString = csb.ConnectionString;
conn.Open();
using (DbCommand cmd = conn.CreateCommand())
{
cmd.CommandText = query;
using (DataTable dt = new DataTable())
{
DbDataAdapter da = factory.CreateDataAdapter();
cmd.CommandType = CommandType.Text;
da.SelectCommand = cmd;
da.Fill(dt);
return dt;
}
}
}
catch (Exception ex)
{
throw new Exception("Error", ex);
}
finally
{
if (conn.State != ConnectionState.Closed)
conn.Close();
}
}
}
In a second time, I have a class containing my various queries.
public class Query
{
public string SQL;
public string query1()
{
this.SQL = "select * from table1"
return this.SQL;
}
public string query2(string param)
{
this.SQL = "select * from table1 where id = '" + param + "' ";
return this.SQL;
}
I wish I could go query1 and / or query2 as parameter of my method GetData.
public DataTable GetData(query1)
{
//...
}
But I do not know how!
Thank you in advance for your help!

Related

SQL commands not working in C# (ASP.NET web forms)

I'm having a trouble with my code.
I'm trying to have the user the ability to submit his email to subscribe to my "notify me" service, I havn't code anything lately so I a bit confused..
I'm trying to Insert, Read, and Update data in my Online SQL Server.. but nothing seems to work! I don't know why I tried everything I know I check a million times it seems good.
Plus if there is any errors my catch should show it to me but even that doesn't work :(
Take a look at this maybe your eyes will see something I don't see.
protected void btnSubmit_Click(object sender, EventArgs e)
{
string cs = ConfigurationManager.ConnectionStrings["notifyCS"].ConnectionString;
using (SqlConnection conn = new SqlConnection(cs))
{
conn.Open();
try
{
string checkEmail = "SELECT User_Email FROM tbl_users WHERE User_Email = #User_Email";
string checkSubscription = "SELECT User_Status FROM tbl_users WHERE User_Email = #User_Email";
string submitEmail = "INSERT INTO tbl_users (User_UID, User_Email, User_Status) VALUES (#User_UID, #User_Email, #User_Status)";
string submitEmail2 = "UPDATE tbl_users SET User_UID = #User_UID, User_Status = #User_Status WHERE User_Email = #User_Email";
SqlCommand emailCMD = new SqlCommand(checkEmail, conn);
SqlDataAdapter emailSDA = new SqlDataAdapter
{
SelectCommand = emailCMD
};
DataSet emailDS = new DataSet();
emailSDA.Fill(emailDS);
//if there is no email registered.
if (emailDS.Tables[0].Rows.Count == 0)
{
SqlCommand registerEmail = new SqlCommand(submitEmail, conn);
string User_UID = System.Guid.NewGuid().ToString().Replace("-", "").ToUpper();
registerEmail.Parameters.AddWithValue("#User_UID", HttpUtility.HtmlEncode(User_UID));
registerEmail.Parameters.AddWithValue("#User_Email", HttpUtility.HtmlEncode(email.Text));
registerEmail.Parameters.AddWithValue("#User_Status", HttpUtility.HtmlEncode("subscribed"));
registerEmail.ExecuteNonQuery();
registerEmail.Dispose();
conn.Close();
conn.Dispose();
email.Text = null;
}
else if (emailDS.Tables[0].Rows.Count > 0)
{
using (SqlCommand checkSub = new SqlCommand(checkSubscription, conn))
{
checkSub.Parameters.AddWithValue("#User_Email", HttpUtility.HtmlEncode(email.Text));
SqlDataReader sdr = checkSub.ExecuteReader();
if (sdr.HasRows)
{
string res = sdr["User_Status"].ToString();
if (res != "subscribed")
{
using (SqlCommand registerEmail2 = new SqlCommand(submitEmail2, conn))
{
string User_UID = System.Guid.NewGuid().ToString().Replace("-", "").ToUpper();
registerEmail2.Parameters.AddWithValue("#User_UID", HttpUtility.HtmlEncode(User_UID));
registerEmail2.Parameters.AddWithValue("#User_Email", HttpUtility.HtmlEncode(email.Text));
registerEmail2.Parameters.AddWithValue("#User_Status", HttpUtility.HtmlEncode("subscribed"));
registerEmail2.ExecuteNonQuery();
registerEmail2.Dispose();
conn.Close();
conn.Dispose();
email.Text = null;
}
}
else
{
conn.Close();
conn.Dispose();
Response.Redirect("index.aspx");
}
}
}
}
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
finally
{
conn.Close();
if (conn.State != ConnectionState.Closed)
{
conn.Close();
conn.Dispose();
}
}
}
}
Try it this way:
using (SqlConnection conn = new SqlConnection(cs))
{
conn.Open();
string checkEmail = "SELECT * FROM tbl_users WHERE User_Email = #User";
SqlCommand emailCMD = new SqlCommand(checkEmail, conn);
emailCMD.Parameters.Add("#User", SqlDbType.NVarChar).Value = email.Text;
SqlDataAdapter da = new SqlDataAdapter(emailCMD);
SqlCommandBuilder daU = new SqlCommandBuilder(da);
DataTable emailRecs = new DataTable();
emailRecs.Load(emailCMD.ExecuteReader());
DataRow OneRec;
if (emailRecs.Rows.Count == 0)
{
OneRec = emailRecs.NewRow();
emailRecs.Rows.Add(OneRec);
}
else
{
// record exists
OneRec = emailRecs.Rows[0];
}
// modify reocrd
OneRec["User_UID"] = User_UID;
OneRec["User_Email"] = email.Text;
OneRec["User_Status"] = "subscribed";
email.Text = null;
da.Update(emailRecs);
}
}

C# connection to oracle DB

I am trying to get a select result and write a simple authentication. But i have some problems with reader.HasRows/table.Rows.Count>0, its always false. Maybe reason not in reader/adapter, but i dont have other ideas
Form1.cs[enter image description here][1]
private void button1_Click(object sender, EventArgs e)
{
String loginUser = loginField.Text;
String paswwordUser = passwordField.Text;
DB db = new DB();
DataTable table = new DataTable();
OracleDataAdapter adapter = new OracleDataAdapter();
OracleCommand command = new OracleCommand();
command.CommandType = CommandType.Text;
command.CommandText = "SELECT * from users where login='#uL' AND pass = '#uP' ";
command.Parameters.Add("#uL", OracleDbType.Varchar2).Value = loginUser;
command.Parameters.Add("#uP", OracleDbType.Varchar2).Value = paswwordUser;
command.Connection = db.GetConnection();
db.openConnection();
// OracleDataReader reader = command.ExecuteReader();
adapter.SelectCommand = command;
table.Load(command.ExecuteReader());
adapter.Fill(table);
if (table.Rows.Count>0)
MessageBox.Show("Yes");
else
MessageBox.Show("No");
// reader.Close();
}
DB.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Oracle.DataAccess.Client;
{
class DB
{
OracleConnection connection = new OracleConnection("Data Source=****/XEPDB1;User Id=****;Password=****;");
public void openConnection()
{
if (connection.State == System.Data.ConnectionState.Closed)
connection.Open();
}
public void closeConnection()
{
if (connection.State == System.Data.ConnectionState.Open)
connection.Close();
}
public OracleConnection GetConnection()
{
return connection;
}
}
}
https://i.stack.imgur.com/8m5ZZ.jpg
try to use colon:
command.CommandText = "SELECT * from users where login=:uL AND pass = :uP ";
command.Parameters.Add("uL", OracleDbType.Varchar2).Value = loginUser;
command.Parameters.Add("uP", OracleDbType.Varchar2).Value = paswwordUser;
command.Connection = db.GetConnection();
db.openConnection();
DataSet dataSet = new DataSet();
using (OracleDataAdapter dataAdapter = new OracleDataAdapter())
{
dataAdapter.SelectCommand = command;
dataAdapter.Fill(dataSet, "Users");
}
var dataTable= dataSet.Tables["Users"];
this.BindingContext[dataTable].EndCurrentEdit();
if(dataSet.HasChanges(DataRowState.Modified))
{
// do your stuff here
}

asp.net web api with Mysql database

I have a background in PHP and bump into a problem while trying out ASP.NET webAPI.
I have a MySQL database and a table that contains some files information.
Now i want to make a "SELECT * FROM Files" and see the result in XML.
How can i render the result of the query that is returned?
This is my code at the moment,
The Model:
namespace ProductsApp.Models
{
public class File
{
public int Id {get; set;}
public string Text {get; set;}
}
}
The Controller:
public IEnumerable<File> Get()
{
try
{
command = conn.CreateCommand();
command.CommandText = "SELECT * FROM Files";
conn.Open();
MySqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
//How to output the rows ????
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
return null; // return the list
}
Making some assumptions about your File Table, this is how you get the data
public IEnumerable<File> Get()
{
List<File> list = new List<File>();
try
{
command = conn.CreateCommand();
command.CommandText = "SELECT * FROM Files";
conn.Open();
using(MySqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
//How to output the rows ????
int id = (int) reader["Id"];//Assuming column name is 'Id' and value if typeof(int)
string text = (string) reader["Text"];//Assuming column name is `Text` and typeof(string)
var file = new File {Id = id, Text = text};
list.Add(file);
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
return list; // return the list
}
As for the xml that is a formatting setting that needs to be allowed on the request.
Given the default setup of WebApi once the client making the call requests text/xml as the content type then the result should be parsed to xml and returned to the client.
If it is you want to force the response to always be xml then you need to make some changes to the response. One way is to set the Content-Type header before returning your result.
Response.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("text/xml;charset=utf-8");
There are other ways you can do this and there are many answers on SO that will be able to show you.
Webconfig:
public static MySqlConnection conn()
{
string conn_string = "server=localhost;port=3306;database=testmvc;username=root;password=root;";
MySqlConnection conn = new MySqlConnection(conn_string);
return conn;
}
Controller :
public MySqlConnection con = WebApiConfig.conn();
public IHttpActionResult GetAllProduct()
{
IList<product> pro = null;
try
{
con.Open();
MySqlCommand cmd = new MySqlCommand("select * from product", con);
cmd.CommandType = CommandType.Text;
MySqlDataAdapter da = new MySqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
pro = ds.Tables[0].AsEnumerable().Select(dataRow => new product { Pname = dataRow.Field<string>("pname"), Pid = dataRow.Field<int>("pid"), Pprice = dataRow.Field<decimal>("pprice") }).ToList();
}
finally
{
con.Close();
}
if (pro.Count == 0)
{
return NotFound();
}
return Ok(pro);
}
public IHttpActionResult PostNewProduct(product pro)
{
try
{
con.Open();
MySqlCommand cmd = new MySqlCommand();
cmd.Connection = con;
cmd.CommandText = "SELECT MAX(pid) from product";
cmd.CommandType = CommandType.Text;
int maxid = Convert.ToInt16(cmd.ExecuteScalar().ToString())+1;
cmd.CommandText = "insert into product values(" + maxid + ",'" + pro.Pname + "'," + pro.Pprice + ")";
cmd.ExecuteNonQuery();
}
finally
{
con.Close();
}
return Ok();
}
public IHttpActionResult PutOldProduct(product pro)
{
string sql = "update product set pname='" + pro.Pname + "',pprice=" + pro.Pprice + " where pid=" + pro.Pid + "";
try
{
con.Open();
MySqlCommand cmd = new MySqlCommand(sql, con);
cmd.CommandType = CommandType.Text;
cmd.ExecuteNonQuery();
}
finally
{
con.Close();
}
return Ok();
}
public IHttpActionResult Delete(int id)
{
string sql = "delete from product where pid=" + id + "";
try
{
con.Open();
MySqlCommand cmd = new MySqlCommand(sql, con);
cmd.CommandType = CommandType.Text;
cmd.ExecuteNonQuery();
}
finally
{
con.Close();
}
return Ok();
}

Set datatables to be equivalent

This is probably a simple question but I am not experienced in C#.
I have 2 datatables, 1 is basically a copy of the other (like a table to review information). To set the values this is what I am doing now:
string attribute1 = "";
string attribute2 = "";
string attribute3 = "";
.....
DataTable result = new DataTable();
using (SqlConnection con = new SqlConnection("user id=user_id;password=pwd;server=serverstring;Trusted_Connection=yes;database=database;connection timeout=30"))
{
using (SqlCommand cmd = new SqlCommand("SELECT * FROM table1 WHERE parameter=#identifying_parameter", con))
{
cmd.Parameters.AddWithValue("#identifying_parameter", "example");
con.Open();
SqlDataReader reader = cmd.ExecuteReader();
if (reader.Read())
{
attribute1 = Convert.ToString(reader["attribute1"]);
attribute2 = Convert.ToString(reader["attribute2"]);
attribute3 = Convert.ToString(reader["attribute3"]);
.....
}
con.Close();
}
}
using (SqlConnection con = new SqlConnection("user id=user_2;password=pwd;server=serverstring;Trusted_Connection=yes;database=database;connection timeout=30"))
{
using (SqlCommand cmd = new SqlCommand("INSERT INTO table2 (attribute1, attribute2, attribute3, ...) VALUES(#attribute1, #attribute2, #attribute3, ...)", con))
{
cmd.Parameters.AddWithValue("#attribute1", attribute1);
cmd.Parameters.AddWithValue("#attribute2", attribute2);
cmd.Parameters.AddWithValue("#attribute3", attribute3);
....
con.Open();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(result);
con.Close();
da.Dispose();
}
}
Obviously I might have a lot of attributes, so is there a simpler way to set every attribute in the table to be equal in C#?
You can use INSERT..INTO..SELECT
DataTable result = new DataTable();
using (SqlConnection con = new SqlConnection("user id=user_2;password=pwd;server=serverstring;Trusted_Connection=yes;database=database;connection timeout=30"))
{
using (SqlCommand cmd = new SqlCommand(#"INSERT INTO table2 (attribute1, attribute2, attribute3, ...)
SELECT attribute1, attribute2, attribute3 ... FROM table1
WHERE parameter=#identifying_parameter
", con))
{
cmd.Parameters.AddWithValue("#identifying_parameter", "example");
con.Open();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(result);
con.Close();
da.Dispose();
}
}
You can use * instead of specifying the column name, although which is not good practice..
In order to make a second Table identical (or "equivalent" as per your definition) to the first one (for certainty let's call it sourceTable), you can use SqlBulkCopy.WriteToServer Method (DataTable)(re: https://msdn.microsoft.com/en-us/library/ex21zs8x%28v=vs.110%29.aspx)
using (SqlConnection YourConnection= new SqlConnection(YourConnectionString))
{
YourConnection.Open();
using (SqlBulkCopy bulkCopy = new SqlBulkCopy(YourConnection))
{
bulkCopy.DestinationTableName = "dbo.YourDestinationTable";
try
{
// Write from the source to the destination.
bulkCopy.WriteToServer(sourceTable);
}
catch (Exception ex) { }
}
}
In order to get a sourceTable you can use the following code snippet:
DataTable sourceTable = SqlReadDB(YourConnString, "SELECT *")
private static DataTable SqlReadDB(string ConnString, string SQL)
{
DataTable _dt;
try
{
using (SqlConnection _connSql = new SqlConnection(ConnString))
{
using (SqlCommand _commandl = new SqlCommand(SQL, _connSql))
{
_commandSql.CommandType = CommandType.Text;
_connSql.Open();
using (SqlCeDataReader _dataReaderSql = _commandSql.ExecuteReader(CommandBehavior.CloseConnection))
{
_dt = new DataTable();
_dt.Load(_dataReaderSqlCe);
_dataReaderSql.Close();
}
}
_connSqlCe.Close();
return _dt;
}
}
catch { return null; }
}
}
Hope this may help.

I need help in query builder c#- delete doesn't work

I have a small project in c# and ms-access. I use query builder to manage my tables in ms-access.
The problem is, select query works great, update query works great, but delete doesn't work and there is no error message!
Please help.
public DataSet Update(DataSet ds)
{
using (cn)
{
OleDbDataAdapter adapter = new OleDbDataAdapter();
string queryString = "SELECT [taskId],[resourceId] FROM [mytable]";
cn.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + _conStrName + ";User Id=admin;Password=;";
OleDbConnection connection = new OleDbConnection(cn.ConnectionString);
adapter.SelectCommand = new OleDbCommand(queryString, connection);
adapter.SelectCommand.CommandText = queryString;
OleDbCommandBuilder builder = new OleDbCommandBuilder(adapter);
adapter.Update(ds.Tables["mytable";"]);
return ds;
}
public DataSet Update(DataSet ds)
{
using (cn)
{
OleDbDataAdapter adapter = new OleDbDataAdapter();
string queryString = "SELECT [taskId],[resourceId] FROM [mytable]";
cn.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + _conStrName + ";User Id=admin;Password=;";
OleDbConnection connection = new OleDbConnection(cn.ConnectionString);
adapter.SelectCommand = new OleDbCommand(queryString, connection);
adapter.SelectCommand.CommandText = queryString;
OleDbCommandBuilder builder = new OleDbCommandBuilder(adapter);
adapter.Update(ds.Tables["mytable";"]);
return ds;
}
==================================
If you are using OleDb try something like:
public static int DeleteStudentInfo(long studentNum)
{
var cmd = new OleDbCommand("DELETE FROM Students WHERE studentID = #studentId");
cmd.Parameters.Add("#studentId", OleDbType.BigInt).Value = studentNum;
return CallNonQuery(cmd);
}
private static int CallNonQuery(OleDbCommand query)
{
int rowsAffected;
var conn = new OleDbConnection(ConfigSettingsManager.DBConnectionString);
query.Connection = conn;
try
{
conn.Open();
rowsAffected = query.ExecuteNonQuery();
}
catch (Exception)
{
return -1;
}
finally
{
conn.Close();
}
return rowsAffected;
}
Replacing ConfigSettingsManager.DBConnectionString with your connection string.
Use:
DELETE FROM Store_Information WHERE store_name = "Los Angeles"

Categories

Resources