I am getting Not all variables Bound.
Here is what My Code Looks Like.
public IEnumerable<VaultService> Get(string Branch_Desg)
{
OracleConnection con = new OracleConnection(constr);
con.Open();
DataTable dt = new DataTable();
//string sql = "select * from wemadummyvaulttable where branch_desg = " + Branch_Desg + "";
string sql = "select BRANCH_ID ,BRANCH_NAME ,BRANCHID_NUMBER ,BRANCH_ACCOUNTNO ,BRANCH_DESG ,CURRENCY ,BRANCH_BALANCE from wemadummyvaulttable where Branch_Desg =" + ":Branch_Desg";
OracleDataAdapter da = new OracleDataAdapter(sql, con);
da.Fill(dt);
List<VaultService> vr = new List<Models.VaultService>(dt.Rows.Count);
if (dt.Rows.Count > 0)
{
foreach (DataRow vaultrecord in dt.Rows)
{
vr.Add(new ReadVaultBal(vaultrecord));
}
}
return vr;
}
For some Reason its not Working like its supposed to.
Screenshot Looks Like this :
Now My Updated Code Looks like this:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using WEMAVaultREST.Models;
using Oracle.ManagedDataAccess.Client;
using Oracle.ManagedDataAccess.Types;
using System.Data;
namespace WEMAVaultREST.Controllers
{
public class VaultServiceController : ApiController
{
string constr = "User ID=system; Password=admin1234; Data Source=SAM;";
// GET api/<controller>
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
// GET api/<controller>/5
public string Get(int id)
{
return "value";
}
// GET api/<controller>/5
/* public VaultService Get(string Branch_Desg)
{
OracleConnection con = new OracleConnection(constr);
con.Open();
DataTable dt = new DataTable();
string sql = "select * from wemadummyvaulttable where branch_desg = '"+Branch_Desg+"'";
OracleDataAdapter da = new OracleDataAdapter(sql,con);
da.Fill(dt);
if (dt.Rows.Count > 0)
{
return new ReadVaultBal(dt.Rows[0]);
}
throw new Exception("Account not found");
}*/
public IEnumerable<VaultService> Get(string Branch_Desg)
{
OracleConnection con = new OracleConnection(constr);
con.Open();
DataTable dt = new DataTable();
//string sql = "select * from wemadummyvaulttable where branch_desg = " + Branch_Desg + "";
string sql = "select BRANCH_ID ,BRANCH_NAME ,BRANCHID_NUMBER ,BRANCH_ACCOUNTNO ,BRANCH_DESG ,CURRENCY ,BRANCH_BALANCE from wemadummyvaulttable where Branch_Desg =" + ":Branch_Desg";
var command = new OracleCommand(sql, con);
command.Parameters.Add("Branch_Desg", Branch_Desg);
OracleDataAdapter da = new OracleDataAdapter(command);
da.Fill(dt);
List<VaultService> vr = new List<Models.VaultService>(dt.Rows.Count);
if (dt.Rows.Count > 0)
{
foreach (DataRow vaultrecord in dt.Rows)
{
vr.Add(new ReadVaultBal(vaultrecord));
}
}
return vr;
}
// POST api/<controller>
public void Post([FromBody]string value)
{
}
// PUT api/<controller>/5
public void Put(int id, [FromBody]string value)
{
}
// DELETE api/<controller>/5
public void Delete(int id)
{
}
}
}
Thats what i have for now. As you can see it Returns in Sqldeveloper.In the Code, it does not. I do not know what and where to Go from here.
If i run the REST api just like this :
http://localhost:7177/api/VaultService?Branch_Desg=Branch01
It returns this
Try replacing the line
OracleDataAdapter da = new OracleDataAdapter(sql, con);
with
var command = new OracleCommand(sql, con);
command.Parameters.Add("Branch_Desg", branchDesg);
OracleDataAdapter da = new OracleDataAdapter(command);
It seems there isn't a way to add bind parameters directly to an OracleDataAdapter, so we have to create an OracleCommand from the SQL string first, add a value for the parameter :Branch_Desg, and then create the adapter from the command.
Finally, can I please recommend that all Oracle resources (connection, command and data-adapter) are disposed correctly, by creating them in using blocks, e.g.
using (OracleConnection con = new OracleConnection(constr))
{
// code using the database connection 'con'
}
Related
I am trying to fill my SQL Server database with 3 different .txt files I accomplished this using regular for but it takes a long time. Then since the order does not matter (in my database) I tried to use Parallel.ForEach but I get this error error
Here is my code
using System;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.Data;
namespace LogwithDataBase
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
SqlConnection con = new SqlConnection(#"Data Source=.\SQLEXPRESS;Initial Catalog=LogsUploaded;Integrated Security=SSPI");
void filldata()
{
SqlDataAdapter da = new SqlDataAdapter("Select *From LogsTable", con);
DataSet ds = new DataSet();
con.Open();
da.Fill(ds, "LogsTable");
dataGridView1.DataSource = ds.Tables["LogsTable"];
dataGridView1.Columns[1].DefaultCellStyle.Format = "yyyy-MM-dd HH:mm:ss.fff";
con.Close();
}
private void datab_connect_Click(object sender, EventArgs e)
{
con.Open();
IEnumerable<string> lines1 = File.ReadLines(openFileDialog1.FileName); //HWLog
Parallel.ForEach(lines1, line1 =>
{
string timeStmp = line1.Split('\t')[0];
string atmIdd = line1.Split('\t')[1];
string fileTyp = "HWLog";
string evenTex = line1.Split('\t')[2];
string query = "INSERT INTO LogsTable (timestampof_log,atmID,fileType,eventText) values (#timeStmp, #atmIdd, #fileTyp, #evenTex)";
SqlCommand cmd = new SqlCommand(query, con);
cmd.Parameters.AddWithValue("#timeStmp", DateTime.Parse(timeStmp));
cmd.Parameters.AddWithValue("#atmIdd", atmIdd);
cmd.Parameters.AddWithValue("#fileTyp", fileTyp);
cmd.Parameters.AddWithValue("#evenTex", evenTex);
cmd.ExecuteNonQuery();
});
IEnumerable<string> lines2 = File.ReadLines(openFileDialog2.FileName); //SWLog
Parallel.ForEach(lines2, line2 =>
{
string timeStmp = line2.Split('\t')[0];
string atmIdd = line2.Split('\t')[1];
string fileTyp = "SWLog";
string evenTex = line2.Split('\t')[2];
string query = "INSERT INTO LogsTable (timestampof_log,atmID,fileType,eventText) values (#timeStmp, #atmIdd, #fileTyp, #evenTex)";
SqlCommand cmd = new SqlCommand(query, con);
cmd.Parameters.AddWithValue("#timeStmp", DateTime.Parse(timeStmp));
cmd.Parameters.AddWithValue("#atmIdd", atmIdd);
cmd.Parameters.AddWithValue("#fileTyp", fileTyp);
cmd.Parameters.AddWithValue("#evenTex", evenTex);
cmd.ExecuteNonQuery();
});
IEnumerable<string> lines3 = File.ReadLines(openFileDialog3.FileName); //JournalLog
Parallel.ForEach(lines3, line3 =>
{
string timeStmp = line3.Split('\t')[0];
string atmIdd = line3.Split('\t')[1];
string fileTyp = "JournalLog";
string evenTex = line3.Split('\t')[2];
string query = "INSERT INTO LogsTable (timestampof_log, atmID, fileType, eventText) VALUES (#timeStmp, #atmIdd, #fileTyp, #evenTex)";
SqlCommand cmd = new SqlCommand(query, con);
cmd.Parameters.AddWithValue("#timeStmp", DateTime.Parse(timeStmp));
cmd.Parameters.AddWithValue("#atmIdd", atmIdd);
cmd.Parameters.AddWithValue("#fileTyp", fileTyp);
cmd.Parameters.AddWithValue("#evenTex", evenTex);
cmd.ExecuteNonQuery();
});
string querycb = "SELECT DISTINCT fileType FROM LogsTable"; //COMBOBOXA DATA ÇEKMEK
SqlCommand cmdcb = new SqlCommand(querycb, con); //COMBOBOXA DATA ÇEKMEK
SqlDataReader drcb = cmdcb.ExecuteReader(); //COMBOBOXA DATA ÇEKMEK
List<string> list = new List<string>(); //COMBOBOXA DATA ÇEKMEK
list.Add(""); //COMBOBOXA DATA ÇEKMEK
while (drcb.Read())
{
list.Add(drcb["fileType"].ToString());
}
drcb.Close();
comboBox1.DataSource = list; //COMBOBOXA DATA ÇEKMEK
con.Close();
filldata();
}
}
}
I couldn't solve this problem and I don't want to go back to regular for
In terms of performance i would suggest to use sqlbulkcopy
Just fill a DataTable with all the lines and insert all at once, its much faster than make a single query for each line in the file thant could be really really long.
public static void BulkInsert(IEnumerable<string> lines)
{
DataTable dt = new DataTable();
dt.TableName = "LogsTable";
dt.Columns.Add("timestampof_log");
dt.Columns.Add("atmID");
dt.Columns.Add("fileType");
dt.Columns.Add("eventText");
foreach (var line in lines)
{
string timeStmp = line.Split('\t')[0];
string atmIdd = line.Split('\t')[1];
string fileTyp = "JournalLog";
string evenTex = line.Split('\t')[2];
dt.Rows.Add(timeStmp, atmIdd, fileTyp, evenTex);
}
BulkInsert(dt);
}
public static void BulkInsert(DataTable table)
{
using (var bulkInsert = new SqlBulkCopy(ConnectionString))
{
bulkInsert.DestinationTableName = table.TableName;
bulkInsert.WriteToServer(table);
}
}
Simplest way - open sql connection in each parallel thread.
Parallel.Foreach SQL querying sometimes results in Connection more detailed here
I want to convert a DataReader to DataTable to display all customers in a list(demoClients) from the Database.
Currently I have this:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using MySqlConnector;
using ProjectDatabase.Controllers;
using System.Data;
using System.Data.Common;
namespace ProjectDatabase.Models
{
public class demoClientsQuery
{
public AppDb Db { get; }
public demoClientsQuery(AppDb db)
{
Db = db;
}
public async Task<demoClients> FindAllClientsAsync(int id)
{
using var cmd = Db.conDemo.CreateCommand();
cmd.CommandText = #"Query";
cmd.Parameters.Add(new MySqlParameter
{
ParameterName = "#id_customer",
DbType = DbType.Int32,
Value = id,
});
MySqlDataReader dataReader = cmd.ExecuteReader();
DataTable dataTable = new DataTable();
dataTable.Load(dataReader);
var result = await ReadAllAsync(dataTable);
return result.Count > 0 ? result[0] : null;
}
public async Task<List<demoClients>> LatestClientsAsync()
{
using var cmd = Db.conDemo.CreateCommand();
cmd.CommandText = #"Query";
var aa = await LatestClientsAsync2();
MySqlDataReader dataReader = cmd.ExecuteReader();
DataTable dataTable = new DataTable();
dataTable.Load(dataReader);
return await ReadAllAsync(dataTable);
}
public async Task<DataTable> LatestClientsAsync2()
{
using var cmd = Db.conDemo.CreateCommand();
cmd.CommandText = #"Query";
//return await ReadAllAsync(await cmd.ExecuteReaderAsync());
return await ToDataTable(cmd);
}
private async Task<DataTable> ToDataTable(MySqlCommand cmd)
{
cmd.CommandType = CommandType.Text;
using (DbDataAdapter dataAdapter = new MySqlDataAdapter(cmd))
{
cmd.CommandType = CommandType.Text;
DataTable data = new DataTable();
dataAdapter.Fill(data);
return data;
}
}
private async Task<List<demoClients>> ReadAllAsync(DataTable dataTable)
{
var adb_demo_clients = new List<demoClients>();
using (dataTable)
{
foreach (DataRow dr in dataTable.Rows)
{
int id_customer = Convert.ToInt32(dr["id_customer"]);
string delivery_person_name = Convert.ToString(dr["delivery_person_name"]);
string firstname = Convert.ToString(dr["firstname"]);
string lastname = Convert.ToString(dr["lastname"]);
string email = Convert.ToString(dr["email"]);
}
}
return adb_demo_clients;
}
}
}
The only problem I am having is that it doesn't return nothing, it returns empty, something in my code is not returning my data from my database.
Any help would be appreciated.
Thank you for your time.
You have to add item to your adb_demo_clients list, inside the foreach, on the ReadAllAsync method:
private async Task<List<demoClients>> ReadAllAsync(DataTable dataTable)
{
var adb_demo_clients = new List<demoClients>();
using (dataTable)
{
foreach (DataRow dr in dataTable.Rows)
{
demoClients d = new demoClients();
d.id_customer = Convert.ToInt32(dr["id_customer"]);
d.delivery_person_name = Convert.ToString(dr["delivery_person_name"]);
// all fields that you need
...
// Add the item in your List
adb_demo_clients.add(d);
}
}
return adb_demo_clients;
}
I have created a class that gets the user details from DB to strings (username,userpassword,usernr,usersubco).
What i want to happen is that those strings fill with the info from the user I login with.
public class Details
{
public connectionUser constring = new connectionUser();
public string Technr;
public string Techpass;
public string Techname;
public string Techsubco;
public Details()
{
using (SqlConnection con = new SqlConnection(constring.source))
{
myInlogForm myI = new myInlogForm();
con.Open();
SqlCommand cmd = new SqlCommand("select * from techs where technr=#technr", con);
cmd.Parameters.Add(#"technr", SqlDbType.Int).Value = myI.technr;
cmd.ExecuteNonQuery();
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
Technr = reader[0].ToString();
Techpass = reader[1].ToString();
Techname = reader[2].ToString();
Techsubco = reader[3].ToString();
break;
}
con.Close();
}
MessageBox.Show(Techname + Technr + Techpass + Techsubco);
}
myI = usercontrol (inlogscreen)
myIn.technummer is a public string that get value on loginbutton from textbox.
when I push login I got the message box from this class above (empty) and following error :
UPDATED !!!
System.Data.SqlClient.SqlException: 'The parameterized query
'(#technr int)select * from techs where technr=#technr' expects the
parameter '#technr', which was not supplied.'
public event EventHandler<EventArgs> callMenu; // oproep door mainform
public event EventHandler<EventArgs> callDash; // oproep door mainform
public int technr;
private void loginBtn_Click(object sender, EventArgs e)
{
using (SqlConnection con = new SqlConnection(cUser.source.ToString()))
{
con.Open();
SqlCommand cmd = new SqlCommand("select technr,techcode from techs where technr=#technr and techcode=#techcode", con);
cmd.Parameters.Add(#"technr",SqlDbType.Int).Value = userTxb.Text;
cmd.Parameters.Add(#"techcode",SqlDbType.VarChar).Value = passTxb.Text;
cmd.ExecuteNonQuery();
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
if (dt.Rows.Count > 0 && callMenu != null && callDash != null) // checks login is juist
{
callMenu(this, new EventArgs());
callDash(this, new EventArgs());
technr = int.Parse(userTxb.Text);
}
else
{
MessageBox.Show("Foutieve gegevens");
}
con.Close();
}
}
try it in this way
cmd.Parameters.Add(#"#technr", SqlDbType.Int).Value = myI.technr;
I am trying to get data as a list from the database but it is not showing any results. I tried to debug but after this line it doesn't let me to step over / F10:
DataSet ds = new DataSet();
da.Fill(ds);
I am trying to do this by following this example on here: link 1 and here link 2 but finding it difficult hence I thought that I should ask here.
Can someone please explain why it is not displaying the results and as such what I may be doing wrong here? how do I work around and achieve it to display the data?
Here's the full controller code for your inspection:
public static List<DBTrack> GetListOfTracks()
{
if (DBTrackData == null)
{
string myConnectionString = "Data Source="; // I have taken off the source
string mySelectString = "SELECT TrackID, AddedDate, TrackName, ArtistName from TBL_Track";
SqlDataAdapter da = new SqlDataAdapter();
DataSet ds = new DataSet();
da.Fill(ds);
OleDbConnection myConnection = new OleDbConnection(myConnectionString);
OleDbCommand myCommand = new OleDbCommand(mySelectString, myConnection);
myCommand.Connection.Open();
OleDbDataReader myReader = myCommand.ExecuteReader(CommandBehavior.CloseConnection);
List<DBTrack> list = new List<DBTrack>();
while (myReader.Read())
{
DBTrack data = new DBTrack();
data.TrackID = (Guid)(myReader["TrackID"]);
data.AddedDate = (DateTime)myReader["AddedDate"];
data.TrackName = (string)myReader["TrackName"];
data.ArtistName = (string)myReader["ArtistName"];
list.Add(data);
};
}
return DBTrackData;
}
EDIT:
SqlConnection mySQLconnection = new SqlConnection(#"Data Source=server-2\SQLExpress;Initial Catalog=End;Integrated Security=False;User ID=test1;Password=**");
SqlCommand mySelectString = new SqlCommand("SELECT TrackID, AddedDate, TrackName, ArtistName from TBL_Track");
using (SqlConnection connection = new SqlConnection("context connection=true"))
{
connection.Open();
using (SqlCommand myCommand = new SqlCommand // The best overload method System.Data.SqlClient.SqlCommand.SqlCommand has some invalid arguments
(mySelectString, mySQLconnection)) // Cannot convert from System.Data.SqlClient.SqlCommand to 'string'
{
You should set the DBTrackData to the result of the list:
while (myReader.Read())
{
...
}
DBTrackData = list;
You could also directly edit the DBTrackData in your code:
private static List<DBTrack> DBTrackData
public static List<DBTrack> GetListOfTracks()
{
if (DBTrackData == null)
{
...
DBTrackData = new List<DBTrack>();
while (myReader.Read())
{
DBTrack data = new DBTrack();
...
DBTrackData.Add(data);
};
}
return DBTrackData;
}
So, in full it should be:
public static List<DBTrack> GetListOfTracks()
{
try
{
if (DBTrackData == null)
{
string myConnectionString = "Data Source="; // I have taken off the source
string mySelectString = "SELECT TrackID, AddedDate, TrackName, ArtistName from TBL_Track";
using (OleDbConnection myConnection = new OleDbConnection(myConnectionString))
{
myConnection.Open();
using (OleDbCommand myCommand = new OleDbCommand(mySelectString, myConnection))
{
OleDbDataReader myReader = myCommand.ExecuteReader(CommandBehavior.CloseConnection);
List<DBTrack> list = new List<DBTrack>();
while (myReader.Read())
{
DBTrack data = new DBTrack();
data.TrackID = (Guid)(myReader["TrackID"]);
data.AddedDate = (DateTime)myReader["AddedDate"];
data.TrackName = (string)myReader["TrackName"];
data.ArtistName = (string)myReader["ArtistName"];
list.Add(data);
}
DBTrackData = list;
}
}
}
return DBTrackData;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
return DBTrackData;
}
Your main problem is that you are using two different ways of getting the data, but the first is only partially implemented. You are using a data adapter and a data reader. Your data adapter isn't even being passed a connection or query, so this is why it is not working. So you can just remove that part of the code.
It's also easier to read if you immediately return when DBTrackData is not null rather than have a big if block over the whole code. You will then have something like:
public static List<DBTrack> GetListOfTracks()
{
if (DBTrackData != null) return DBTrackData;
string myConnectionString = "Data Source="; // I have taken off the source
string mySelectString = "SELECT TrackID, AddedDate, TrackName, ArtistName from TBL_Track";
OleDbConnection myConnection = new OleDbConnection(myConnectionString);
OleDbCommand myCommand = new OleDbCommand(mySelectString, myConnection);
myCommand.Connection.Open();
OleDbDataReader myReader = myCommand.ExecuteReader(CommandBehavior.CloseConnection);
List<DBTrack> list = new List<DBTrack>();
while (myReader.Read())
{
DBTrack data = new DBTrack();
data.TrackID = (Guid)(myReader["TrackID"]);
data.AddedDate = (DateTime)myReader["AddedDate"];
data.TrackName = (string)myReader["TrackName"];
data.ArtistName = (string)myReader["ArtistName"];
list.Add(data);
};
//Setting DBTrackData means these values will get returned on every call to GetListOfTracks for this instance of the class
DBTrackData = list;
return list;
}
Im new to using ASP.NET and would like to know how I can select a random row from a sql database and then display the fields in a html table on a separate page. It is intended that the user can press on button which will retrieve a random movie from the database and then display the movie details in a html table on a new page. I am not sure how to go about this and have been trying to use labels to display the data. Here is a sample of the code so far:
private SqlConnection conn;
protected void Page_Load(object sender, EventArgs e)
{
ConnectionStringSettings connString = ConfigurationManager.ConnectionStrings ["MovieAppConnectionString1"];
conn = new SqlConnection(connString.ConnectionString);
}
protected void ImageButton1_Click(object sender, ImageClickEventArgs e)
{
try
{
conn.Open();
string queryString = "SELECT TOP 1 * FROM Movie ORDER BY NEWID()";
SqlCommand cmd = new SqlCommand(queryString, conn);
{
SqlDataReader reader = cmd.ExecuteReader();
StringBuilder MyStringBuilder = new StringBuilder();
while (reader.Read())
{
Image2.Text = reader[2].ToString();
Label1.Text = reader[1].ToString();
Desc.Text = reader[3].ToString();
Direc.Text = reader[5].ToString();
Strs.Text = reader[7].ToString();
Rtime.Text = reader[4].ToString();
ImdbRt.Text = reader[8].ToString();
}
}
}
finally
{
conn.Close();
}
Server.Transfer("MovieSelected.aspx");
Change your sql server query from :
SELECT TOP 1 * FROM Movie ORDER BY NEWID()
to
SELECT TOP 1 * FROM Movie ORDER BY RAND()
In your aspx.cs file:
int iLength = 0;
int index = 0;
DataTable dt = new DataTable();
dt = SqlComm.SqlDataTable("SELECT * FROM Movie");
object obj = new object();
obj = SqlComm.SqlReturn("SELECT COUNT (yourTargetColumn) FROM yourTable");
if (obj != null)
iLength = Convert.ToInt32(obj);
string[] stringArray = new string[iLength];
for (index = 0; index < iLength; index++)
{
stringArray[index] = (string)dt.Rows[index]["yourTargetColumn"];
}
foreach (string strArray in stringArray)
{
Label yourLabel = new Label();
PH.Controls.Add(yourLabel);
}
In your .aspx file:
<asp:PlaceHolder ID="PH" runat="server"></asp:PlaceHolder>
Add a class to your App_Code folder named "SqlComm.cs":
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Data.SqlClient;
public class SqlComm
{
static string DatabaseConnectionString = "your connection string";
public static object SqlReturn(string sql)
{
using (SqlConnection conn = new SqlConnection(DatabaseConnectionString))
{
conn.Open();
SqlCommand cmd = new SqlCommand(sql, conn);
object result = (object)cmd.ExecuteScalar();
return result;
}
}
public static DataTable SqlDataTable(string sql)
{
using (SqlConnection conn = new SqlConnection(DatabaseConnectionString))
{
SqlCommand cmd = new SqlCommand(sql, conn);
cmd.Connection.Open();
DataTable TempTable = new DataTable();
TempTable.Load(cmd.ExecuteReader());
return TempTable;
}
}
Note: Do not forget to add the using System.Data.SqlClient to your code. Also, you just have to customize the SELECT command in order to get the data you want.