C# sqlDataAdapter issue - c#

all I try to load data from sql by following code using SQL server. I checked connection is normal and most sql are available to load. But in certain cases, I can't load data with following error:
"The conversion of the varchar value '2863289685' overflowed an int column.
The statement has been terminated."
and that sql is runnable in sql server management studio, but can't load by following code, please help me with possible solution, thanks!
try
{
SqlCommand command = new SqlCommand(sql, conn);
command.CommandTimeout = 0;
SqlDataAdapter sqlDa = new SqlDataAdapter(command);
DataSet ds = new DataSet();
sqlDa.Fill(ds);
Console.WriteLine(ds.Tables.Count);
dt = ds.Tables[0];
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}

Related

How do I sync data from a database to a combobox

I'm creating a form of which I have to show the data from a database into a combo box and I need help to do it, please
I have already tried to download MySql Server, however, it only supports up to Visual Studio 2017 and I have Visual Studio 2019
using (SqlConnection conn = new SqlConnection(#"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Code\C#\MyFirstUI\MyFirstUI\LOGIN.mdf;Integrated Security=True"))
{
try
{
string query = "select USERNAME from LOGIN";
SqlDataAdapter da = new SqlDataAdapter(query, conn);
conn.Open();
DataSet ds = new DataSet();
da.Fill(ds, "Username");
comboBox3.DisplayMember = "Userame";
comboBox3.DataSource = ds.Tables["Username"];
}
catch (Exception ex)
{
// write exception info to log or anything else
MessageBox.Show(ex.Message,"Error occured!");
}
}
I would have expected the data from the database however, I got an output of nothing
Set comboBox3.ValueMember="USERNAME" and comboBox3.DisplayMember="USERNAME" , Use "USERNAME", not "Userame", because your sql is select USERNAME
Check if ds.Tables["Username"].Rows.Count>0

Reportviewer with MySQL stored procedure. Report not showing data (winform)

I built a form that contains a report viewer and also created a stored procedure in MySQL workbench 8.0. The procedure was tested and works ok. Here is my code:
private void LoadReport()
{
try
{
MySqlParameter quote = new MySqlParameter();
quote = new MySqlParameter("quote", SqlDbType.VarChar);
quote.Value = quote_id_box.Text;
MySqlConnection con = new MySqlConnection(conSettings.ToString());
MySqlCommand cmd = new MySqlCommand();
con.Open();
cmd.Connection = con;
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "project_report";
cmd.Parameters.Add(quote);
MySqlDataReader dr = cmd.ExecuteReader();
DataTable dt = new DataTable();
DataSet ds = new DataSet();
dt.Load(dr);
cmd.ExecuteNonQuery();
Microsoft.Reporting.WinForms.ReportDataSource rds = new Microsoft.Reporting.WinForms.ReportDataSource("pr_DataSet", dt);
this.reportViewer1.LocalReport.DataSources.Add(rds);
this.reportViewer1.RefreshReport();
con.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
The dataTable is getting a response from MySQL and it has the right data in it but the problem is that the report won't show the information. It gives me
"the report source has not been defined"
Any ideas on what i'm doing wrong? This is my first report ever using report viewer. Any help would be greatly appreciated. Thanks

c# Select sql database data using datetimepicker set with date range

I am trying to make c# program, where I have to make a database report to be previewed at the datagridview. Data will be selected using the datetimepicker. I have written the code, it works but then if the date selected is of different months. No records appear
void FilterDBbtnClick(object sender, EventArgs e)
{
MySqlConnection conn = new MySqlConnection();
conn = new MySqlConnection(cs);
string data = "SELECT `Date`, `Process`, `Actual`, `Target` FROM `database` WHERE `Date` BETWEEN '"+this.fromDatePicker.Value+"' AND '"+this.toDatePicker.Value+"' order by `Date` desc";
MySqlCommand cmd = new MySqlCommand(data, conn);
cmd.Connection.Open();
try
{
MySqlDataAdapter sda = new MySqlDataAdapter();
sda.SelectCommand = cmd;
DataSet dt = new DataSet();
sda.Fill(dt);
BindingSource bsource = new BindingSource();
bsource.DataSource = dt;
mondeDataTable.DataSource = dt.Tables[0];
sda.Update(dt);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
cmd.Connection.Close();
}
please help me check my code and tell me what might be wrong or missing.
Use profiler to check the query that hits the DB. I suspect it's a date formatting issue.
Maybe this question can help you with logging the queries that hit the database:
Hope this helps:
Select * from [Table] where StartDate between '06/13/2016' and '10/13/2016'
The above query fetches records between months 06 and 10. Make sure that string in the data variable is in the above format. Also the column type in the database is date.
Check and remove special characters, if any.
Mark this as answer if you find this useful.
Try this for your select query. I have changed one of your select variable because it ambiguous for the Date datatype.
void FilterDBbtnClick(object sender, EventArgs e)
{
MySqlConnection conn = new MySqlConnection();
conn = new MySqlConnection(cs);
//string data = "SELECT `Date`, `Process`, `Actual`, `Target` FROM `database` WHERE `Date` BETWEEN '"+this.fromDatePicker.Value+"' AND '"+this.toDatePicker.Value+"' order by `Date` desc";
//Changed query for getting data from DB according to the date
string data = "SELECT CreatedDate, Process, Actual, Target FROM database WHERE DATE_FORMAT(CreatedDate,'%Y-%m-%d') BETWEEN '"+this.fromDatePicker.Value.ToString("yyyy-MM-dd")+"' AND '"+this.toDatePicker.Value.ToString("yyyy-MM-dd")+"' order by CreatedDate desc";
MySqlCommand cmd = new MySqlCommand(data, conn);
cmd.Connection.Open();
try
{
MySqlDataAdapter sda = new MySqlDataAdapter();
sda.SelectCommand = cmd;
DataSet dt = new DataSet();
sda.Fill(dt);
BindingSource bsource = new BindingSource();
bsource.DataSource = dt;
mondeDataTable.DataSource = dt.Tables[0];
sda.Update(dt);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
cmd.Connection.Close();
}

Procedure or function sp_select_companydetails has too many arguments specified

I am really get depressed about this error all function code is correct but still its giving me the error, I am trying to select information from SQL Server database.
Stored procedure:
create procedure sp_select_companydetails
#id varchar(5)
as
begin
select company_name, company_address
from CompanyDetails
end
C# Code:
2) On Form button click event
string id = "1";
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "sp_select_companydetails";
cmd.Parameters.Add("#id", id);
FillDataset();
In class
public DataSet FillDataset()
{
try
{
using (cmd)
{
DataSet ds = new DataSet();
cmd.Connection = con;
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(ds);
cmd.Parameters.Clear();
return ds;
}
}
catch (Exception)
{
throw;
}
}
When I click on form button I get this error:
Procedure or function sp_select_companydetails has too many arguments specified.
Suggest me good solution
Thank you in advance
Instead of using a global SqlCommand, create it as new everytime you need it. This is a recommended approach when you deal with disposable objects
using (SqlConnection con = new SqlConnection(GetConnectionString())
using (SqlCommand myCmd = new SqlCommand("sp_select_companydetails", con))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#id", SqlDbType.VarChar).Value = "1";
DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(ds);
return ds;
}
By the way, we cannot see how do you create the SqlConnection, but it seems that you have another disposable object kept at the global level. This is particular nasty with an SqlConnection because this object keeps references to system wide resources both on client and on server. Do not create global connection objects, just create a global method that returns the current connectionstring to use in creation of the local SqlConnection (the GetConnectionString() in my example above). If you think that this is a performance killer I suggest you to read about the concept of connection pooling

DataBinding is very slow

I am using Windows application c#. When I bind the data table to Datagridview it gets slow and I am getting a SQL connection timeout error.
At the same time my data table has bulk records. How can I solve this problem?
Code:
private void Window_Loaded(object sender, RoutedEventArgs e)
{
con.StatisticsEnabled = true;
con.Open();
DataTable dt = new DataTable();
SqlCommand cmd = new SqlCommand("select * from Stktrn_table", con);
SqlDataAdapter adp = new SqlDataAdapter(cmd);
adp.Fill(dt);
GridDisplay.ItemsSource = dt.DefaultView;
}
SqlCommand cmdVoid = new SqlCommand("select party_no, smas_rtno,convert(numeric(18,2),SUM(smas_NetAmount)) as Amount from salmas_table where ctr_no=#tCounter and Smas_Cancel<>1 and smas_rtno<>0 and Smas_billdate=#tDate group by smas_rtno, party_no", con);
cmdVoid.Parameters.AddWithValue("#tDate", dpBillDate.SelectedDate.Value);
cmdVoid.Parameters.AddWithValue("#tCounter", tCounterNoNew);
SqlDataAdapter adpVoid = new SqlDataAdapter(cmdVoid);
adpVoid.Fill(dtVoid);
This line
SqlCommand cmd = new SqlCommand("select * from Stktrn_table", con);
Will be your problem. Do not select all rows from the database, limit it using TOP
SELECT TOP 100 Column1, Column2, Column3 FROM Stktrn_table
in general SELECT * is bad practice.
Or alternatively, implement paging so the rows are loaded on demand rather than upfront.
How does the query run within SQL Server management studio? This should be your initial indicator of how long the query will return from the database.
You could also use a stored procedure which may give you a performance benefit over a raw SQL query.
First thing You should not use like this Select * from table_name instead this you should use select column_1,column_2,column3,column_n i.e. select only columns which you needed.
Second thing always use classes(BLL and DLL) instead of coding directly for database at page load or any form.
Third always use try catch block.
Third thing whenever you create a object, you should dispose that in finally block of try catch.
for ex.
DataTable dt = null;
SqlDataAdapter da = null;
SqlConnection con = null;
try
{
con=new SqlConnection("Connection_Source");
con.Open();
da = new DataAdapter("select * from table_name",con);
dt=new DataTable();
da.Fill(dt);
dataGridViewObj.DataSource=dt;
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
if(con.State==ConnectionState.Open)
con.Close();
dt.Dispose();
if(dt!=null)
dt=null;
da.Dispose();
if(da!=null) da=null;
}

Categories