I am encountering some issues when it comes to getting back data from my c# database query
this is my code for the query :
using System;
using System.Text;
using System.Data;
using System.Data.SQLite;
namespace Cryptomoney
{
class DataClass
{
private static SQLiteConnection sqlite;
public DataClass()
{
sqlite = new SQLiteConnection("Data Source= DataCrypto.sqlite3;Version=3;New=False;");
}
public SQLiteDataReader SelectQuery(string query)
{
try
{
sqlite.Open(); //Initiate connection to the db
SQLiteCommand sqlComm = sqlite.CreateCommand();
sqlComm.CommandText = query;
SQLiteDataReader r = sqlComm.ExecuteReader();
sqlite.Close();
}
catch (SQLiteException ex)
{
Console.WriteLine(ex);
}
sqlite.Close();
return r;
}
}
}
and this is the code with the sql :
var b = dataClass.SelectQuery("SELECT PercChange1h FROM DataCrypt WHERE ID = 1");
I want b to be a float, the same type as PercChange1h is in my database but I only get "System.Data.SQLite.SQLiteDataReader".
I already tried :
var b = (float)dataClass.SelectQuery("SELECT PercChange1h FROM DataCrypt WHERE ID = 1")["PercChange1h"]
which returns an error "row does not exist". And all other types of casts do not work ((int), ToString())
My code is nearly the same with create or ALTER or INSERT and it works just fine (but I do not have to get back data"
var cmd = new SQLiteCommand();
cmd = sqlite.CreateCommand();
cmd.CommandText = query; //set the passed query
cmd.ExecuteNonQuery();
Do you know how I could get back a type like string or float from my sqlite db with c# ?
(this is my first question ever so if there is not enough data, I am here to answer)
Have a nice day!
Your function should look like this
public object QueryScalarValue(string query)
{
try
{
sqlite.Open(); //Initiate connection to the db
using(SQLiteCommand sqlComm = new SQLiteCommand(query, sqlite))
return sqlComm.ExecuteScalar();
}
catch (SQLiteException ex)
{
Console.WriteLine(ex);
}
finally
{
sqlite.Close();
}
return r;
}
Then you simply cast the result
var b = (double)dataClass.SelectQuery("SELECT PercChange1h FROM DataCrypt WHERE ID = 1");
I'm new in ASP.Net development, and facing problem in sending data from webService to webform. I'm using JSON method,but in following line of code I'm having issue. The compiler shows this error message.
"Error 3 Invalid token '(' in class, struct, or interface member
declaration
Can someone tell me what is the problem?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Script.Serialization;
using System.Configuration;
using System.Data.SqlClient;
using System.Data;
using System.Runtime.Remoting.Contexts;
using System.Runtime.Remoting;
/// <summary>
/// Summary description for GetStudent
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
[System.Web.Script.Services.ScriptService]
public class GetStudent : System.Web.Services.WebService {
[WebMethod]
public GetStudent () {
//Uncomment the following line if using designed components
//InitializeComponent();
}
[WebMethod]
public void GetStudent () {
SqlConnection con = new SqlConnection("Data Source=(LocalDB)\\v11.0;AttachDbFilename='C:\\Users\\Abdul Basit Mehmood\\Documents\\Visual Studio 2012\\WebSites\\WebSite1\\App_Data\\Database.mdf';Integrated Security= True");
List<StudentsList> stu = new List<StudentsList>();
con.Open();
SqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "Select * From Student";
SqlDataReader DR = cmd.ExecuteReader();
while (DR.Read())
{
StudentsList student = new StudentsList();
student.Id = Convert.ToInt32(DR["Id"]);
student.name = DR["name"].ToString();
student.fname = DR["fname"].ToString();
student.email = DR["email"].ToString();
student.contact = DR["contact"].ToString();
student.Pname = DR["Pname"].ToString();
student.Cname = DR["Cname"].ToString();
StudentsList.Add(student);
}
JavaScriptSerializer js = new JavaScriptSerializer(StudentsList());
Context.Response.Write(js.Serializ(StudentsList));
}
}
Here is how you need to fix your GetStudent method -
[WebMethod]
public void GetStudent () {
SqlConnection con = new SqlConnection("Data Source=(LocalDB)\\v11.0;AttachDbFilename='C:\\Users\\Abdul Basit Mehmood\\Documents\\Visual Studio 2012\\WebSites\\WebSite1\\App_Data\\Database.mdf';Integrated Security= True");
List<StudentsList> stu = new List<StudentsList>();
con.Open();
SqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "Select * From Student";
SqlDataReader DR = cmd.ExecuteReader();
while (DR.Read())
{
StudentsList student = new StudentsList();
student.Id = Convert.ToInt32(DR["Id"]);
student.name = DR["name"].ToString();
student.fname = DR["fname"].ToString();
student.email = DR["email"].ToString();
student.contact = DR["contact"].ToString();
student.Pname = DR["Pname"].ToString();
student.Cname = DR["Cname"].ToString();
stu.Add(student); //Changed line: Changed variable name to stu which is the list variable declared earlier.
}
JavaScriptSerializer js = new JavaScriptSerializer(); //changed line : Removed the invalid parameter to the constructor of JavaScriptSerializer class
Context.Response.Write(js.Serializ(stu)); //changed line : Used the correct stu list variable declared at the starting of the method.
}
Note: Please follow extreme caution while naming your class. Your StudentList entity isn't a list but an individual student entity with various properties like Id,name,fname etc. Please consider renaming it to Student.
In order to validate that you aren't getting any invalid characters from your database first try running if below code works fine or not?
class Program
{
static void Main(string[] args)
{
List<StudentsList> stu = new List<StudentsList>();
StudentsList student = new StudentsList();
student.name = "Abdul Basit Mehmood";
student.fname = "Abdul";
stu.Add(student);
JavaScriptSerializer js = new JavaScriptSerializer();
var serializedValue = js.Serialize(stu);
}
}
class StudentsList
{
public string name;
public string fname;
}
serializedValue variable should show you a valid JSON string in quick watch window as shown below:
I have searched everywhere but cannot figure out what is wrong here. I have a webb c# app. I have a c# method in the app folder where I query a database and then want to pass that value back to my Cshtml page where I will be makin deciaions based on the value. No matted what I do, when I call the method and then try to read the value I get the error "Cannot implicitly convert type 'class1' to string.
Here is my c#class method and below the calls
Method:
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public class class1
{
public static string getdata()
{
string cnnString = ConfigurationManager.ConnectionStrings["GDC_WellsFargoConnectionString"].ConnectionString;
SqlDataReader reader;
string returnValue;
/// var cmd = "insert into Email Insert values(#name,#email";
string userName = System.Security.Principal.WindowsIdentity.GetCurrent().Name;
using (SqlConnection cnn = new SqlConnection(cnnString))
{
using (SqlCommand cmd = new SqlCommand("Select isnull([Authorization],'none') as authoriztion from PNSWebAuthorization where username = '" + userName + "'", cnn))
{
////cmd.Parameters.AddWithValue("#name", "Newname,First");
//// cmd.Parameters.AddWithValue("#email", "Newemail#gibsondunn.com");
///string authcode;
cnn.Open();
try {
reader = cmd.ExecuteReader();
if (reader.Read())
{
returnValue = reader["Authorization"].ToString();
reader.Close();
return returnValue;
}
else
{
reader.Close();
return "";
}
}
catch (Exception err)
{
throw new ApplicationException(err.Message);
}
finally
{
cnn.Close();
cnn.Dispose();
}
}
}
}
CSHTML Calling
#model GDC.Finance.WebClient.Areas.Treasury.ViewModels.CashReceiptSessionListViewModel
#using PagedList.Mvc;
#{
ViewBag.Title = "Cash Receipt Sessions test";
}
<h2>Sessions</h2>
#section scripts{
<script src="~/Scripts/popup.js"></script>
}
#{
/// string auth = "none";
var auth = new class1();
class1.getdata();
string rights = auth;
}
Auth throws the error.
Looks like "public static string getdata()" is a static method.
why not try calling it this way:
var auth = class1.getdata();
Im very new on C#
I Only create 1 Form that Can insert Data to Mysql Database. My code not have Error, but data cant enter the Database. I m so confused.
this my code
Koneksi.cs
using System;
using System.Data;
using MySql.Data.MySqlClient;
using System.Drawing;
using System.Windows.Forms;
namespace timbangan
{
public class Koneksi
{
public MySqlConnection konek;
//string konfigKoneksi = "server=localhost; database=timbangan; uid=root; pwd=";
string konfigKoneksi = "Server=localhost;Database=timbangan;Uid=root;Pwd=";
public void bukaKoneksi()
{
konek = new MySqlConnection(konfigKoneksi);
konek.Open();
var temp = konek.State.ToString();
if (temp == "Open")
{
MessageBox.Show(#"Connection working.");
}
else {
MessageBox.Show(#"Please check connection string");
}
}
public void tutupKoneksi()
{
konek = new MySqlConnection(konfigKoneksi);
konek.Close();
}
}//end of koneksi
}//end namespace
Isidata.cs File
using System;
using System.Data;
using MySql.Data.MySqlClient;
using System.Windows.Forms;
namespace timbangan
{
public class Isidata
{
MySqlDataAdapter adapter;
MySqlCommand komand;
Koneksi classKoneksi;
DataTable tabel;
string sql = "";
public DataTable tambahData(string berat_filter, string qty, string nama_barang, string dari, string shift)
{
classKoneksi = new Koneksi();
sql = "insert into tb_timbang(BERAT_FILTER,QTY,NAMA_BARANG,DARI,SHIFT) values (" + berat_filter + ",'" + qty + "','" + nama_barang + "','" + dari + "','" + shift + "')";
//MessageBox.Show(sql);
tabel = new DataTable();
try
{
classKoneksi.bukaKoneksi();
komand = new MySqlCommand(sql);
adapter = new MySqlDataAdapter(sql, classKoneksi.konek);
adapter.Fill(tabel);
}
catch (Exception)
{
MessageBox.Show("error");
}
return tabel;
}
}//end of issdata
}//end of timbangan
Form1.cs File
using System;
using System.Drawing;
using System.Windows.Forms;
using System.Data;
namespace timbangan
{
public partial class Form1 : Form
{
public DataTable tabel;
public string status = "";
public string berat_filter, qty, nama_barang, dari, shift;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Isidata isi = new Isidata();
tabel = isi.tambahData(tbBerat.Text, tbQty.Text, tbNama.Text, tbDari.Text, tbShift.Text);
MessageBox.Show("Berhasil");
}
}
}
Can Anyone Help me to Fix this? or Advice me to have more short code to Insert data?
Thanks in advance
You could redesign your classes to something like this
namespace timbangan
{
public static class Koneksi
{
public static MySqlConnection konek;
private static string konfigKoneksi = "Server=localhost;Database=timbangan;Uid=root;Pwd=";
public static MySqlConnection GetConnection()
{
konek = new MySqlConnection(konfigKoneksi);
konek.Open();
}
}//end of koneksi
public class Isidata
{
public int InsertData(string berat_filter, string qty, string nama_barang, string dari, string shift)
{
sql = #"insert into tb_timbang
(BERAT_FILTER,QTY,NAMA_BARANG,DARI,SHIFT)
values (#berat_filter,#qty,#nama_barang,#dari,#shift)";
try
{
using(MySqlConnection cnn = Koneksi.GetConnection())
using(MySqlCommand cmd = new MySqlCommand(sql, cnn))
{
cmd.Parameters.Add("#berat_filter", MySqlDbType.VarChar).Value = berat_filter;
cmd.Parameters.Add("#qty", MySqlDbType.VarChar).Value = qty;
cmd.Parameters.Add("#name_barang", MySqlDbType.VarChar).Value = nama_barang;
cmd.Parameters.Add("#dari", MySqlDbType.VarChar).Value = dari;
cmd.Parameters.Add("#shift", MySqlDbType.VarChar).Value = shift;
return cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
MessageBox.Show("error " + ex.Message);
return -1;
}
}
}
}//end of issdata
}//end of timbangan
In this design there are no more global variables around. The same Koneski class could be totally removed and your MySqlConnection could be created on the spot (reading the connectionstring from an external source like your config file). Don't think this is less efficient than keeping a global connection object already created and always open. There is an ADO.NET Connection Pooling infrastructure (link is for Sql Server but it is the same for MySql) that runs very efficiently to handle your connections
The important thing is the Using Statement (that closes and dispose the command and the connection when no more needed freeing valuable resources) and the parameters used to fill the command sent to the server. If you need to use an Adapter for other aspect of your work you could add other methods like this to your Isidata class
As a last note, notice that all parameters are of string type. This could work but it is best to have parameters of the same type of the field type on the database (and of course your variables should be of the correct datatype). This is particularly important with datetime fields that when are treated as strings could give a good headache to let them work correctly) See MySqlDbType enum
Make a class named DBClass.cs and write the below code-
class DBClass
{
MySqlCommand odcmd = new MySqlCommand();
MySqlConnection odcon = new MySqlConnection();
MySqlDataAdapter oda = new MySqlDataAdapter();
public DBClass()
{
}
public void OpenConnection()
{
odcon.ConnectionString = "Server=localhost;Database=timbangan;Uid=root;Pwd=";
if (odcon.State == ConnectionState.Closed)
odcon.Open();
oda.SelectCommand = odcmd;
odcmd.Connection = odcon;
}
public void CloseConnection()
{
if (odcon.State == ConnectionState.Open)
odcon.Close();
}
public DataTable Select(string sql)
{
DataTable dt = new DataTable();
odcmd.CommandText = sql;
oda.Fill(dt);
return dt;
}
public int ModiFy(string sql)
{
odcmd.CommandText = sql;
return odcmd.ExecuteNonQuery();
}
}
On your form, Now you can fire your query like-
DbclassObject.Modify(Your_Insert_Update_Delete_Query);
DataTable dt= DbclassObject.Select(Your_Select_Query);
I have encountered a problem with getting locked out of SQLite file.
I am currently working on employee register for my company and use SQLite as a database of choice. From my program, I populated the database using scripts I prepared. Reading goes well and all, but once I make any change to the employee at all, the program freezes at "database is locked" exception.
I created a static class called SQLiteManager where I have all methods involving the DB. I then call them from Windows Forms like
foreach (Employee em in SQLiteManager.getEmployees()){
//filling the fields }
calls
public static List<Employee> getEmployees() {
List<Employee> ret = new List<Employee>();
SQLiteDataReader reader;
using (SQLiteConnection dbc = new SQLiteConnection(databaseConnectionString))
using (SQLiteCommand cmd = dbc.CreateCommand())
{
openConnection(dbc);
cmd.CommandText = "select ID_Employee from Employee";
reader = cmd.ExecuteReader();
while (reader.Read()) { ret.Add(extractEmployee(reader["ID_Employee"].ToString(), false)); }
}
return ret;
}
I always use this "using" notations in ALL other methods that call ExecuteReader() in them.
Method that I use to crunch the script and populate the DB:
public static bool processSqlCommandFile(string file)
{
try
{
using (StreamReader sr = new StreamReader(file))
{
string line;
while ((line = sr.ReadLine()) != null)
{
using (SQLiteConnection dbc = new SQLiteConnection(databaseConnectionString))
using (SQLiteCommand cmd = dbc.CreateCommand())
{
openConnection(dbc);
cmd.CommandText = line;
cmd.ExecuteNonQuery();
}
}
sr.Close();
}
}
catch (Exception ex)
{
return false;
}
return true;
}
and finally, the sore method
public static bool alterEmployee(Employee e) {
using (SQLiteConnection dbc = new SQLiteConnection(databaseConnectionString))
using (SQLiteCommand cmd = dbc.CreateCommand())
{
openConnection(dbc);
cmd.CommandText = "Update Employee SET name = '"+e.name+"' where ID_Employee = "+e.id;
//Alter the command once this shiet works
cmd.ExecuteNonQuery();
}
return true;
}
Yet it always gets frozen. By using the using(SQLiteConnection...) I thought I am getting rid of the "sleepy" connections that would somehow lock it, but the trouble is somewhere else.
Can you help me identify the problem or tell me steps to identify it myself?
Thank you