The error related in project of linkage c# with SQL - c#

I wrote a C# program to output the contents what is contained in database tables, but when I append conn.open(), dialog box doesn't be created although there isn't any compile error. I already checked whether or not the setting of database information such as ip address, user name, pass word, and database name, but there isn't any misses. I wonder why it isn't executed as soon as appending conn.open():
public static string constring = "Data Source= 192.168.0.21; User=root; Password=admin;database=hwg;";
SqlConnection conn = new SqlConnection();
private string strConnString = "";
[public void ConnectDB]
strConnString = constring;
if (conn.State.ToString().Equals("Closed"))
{
conn.ConnectionString = strConnString;
conn.Open(); //problem on this line
if (conn.State == ConnectionState.Open)
{
}
else
{
conn.Close();
}
}
[public DataTable GetDBTable(string sql)]
SqlDataAdapter adapter = new SqlDataAdapter(sql, conn);
SqlCommandBuilder builder = new SqlCommandBuilder(adapter);
DataTable dt = new DataTable();
adapter.Fill(dt);
return dt;
[public Form1()]
InitializeComponent();
db = new Con_database();
db.ConnectDB();
[private void button1_Click(object sender, EventArgs e)]/*If we click button1, the overall contents of applied table in database hwg is listed*/
string sql = "SELECT * FROM id_repository";
DataTable dt = db.GetDBTable(sql);
DatabaseInquiry.DataSource = dt;
db.ClosedDB();

I think you need to define USERID instead of USER in your connection string.
Old connection string:
public static string constring
= "Data Source= 192.168.0.21; User=root; Password=admin;database=hwg;";
New connection string:
public static string constring =
"Data Source= 192.168.0.21;Initial Catalog="your database name"; UserID=root; Password=admin;";

Related

updating database and using data table and data adapter

what is wrong with the following code? The database does not update and else{} gets executed always. The database does contain 1 row with the field password!
protected void Button1_Click(object sender, EventArgs e)
{
string connectionString = #"Data Source = (localdb)\MSSQLLocalDB; Initial Catalog = db1; Integrated Security = True";
SqlConnection cnn = new SqlConnection(connectionString);
String sql = "update table1 set password = 'hello'";
SqlCommand command = new SqlCommand(sql, cnn);
SqlDataAdapter da = new SqlDataAdapter(command);
DataTable dt = new DataTable();
da.Fill(dt);
cnn.Open();
command.ExecuteNonQuery();
cnn.Close();
if (dt.Rows.Count > 1)
{
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "alertMessage", "alert('Password Reset Successful! Redirecting to Homepage!')", true);
Response.Redirect("testlogin.aspx");
}
else
{
Label1.Text = "Invalid Details";
}
}

c# local Cannot open database requested by the login. The login failed. Login failed for user MicrosoftAccount\(email)

Doesnt connect to database, its throw exception.
SqlConnection con = new SqlConnection("Data Source=.;InitialCatalog=CAFETERIADB; Integrated Security=True;");
SqlCommand cmd;
SqlDataAdapter da;
DataTable dt;
DataSet ds = new DataSet();
private void CashForm_Load(object sender, EventArgs e)
{
con.Open();
da = new SqlDataAdapter("Select * FROM PhoneBook ORDER BY SLNo desc", con);
dt = new DataTable();
da.Fill(dt);
dataGridView1.DataSource = dt;
dataGridView1.Columns[0].Width = 10;
con.Close();
comboBox1.Items.Clear();
con.Open();
cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT Name FROM PhoneBook order by SLNo asc";
cmd.ExecuteNonQuery();
dt = new DataTable();
SqlDataAdapter da1 = new SqlDataAdapter(cmd);
da1.Fill(dt);
foreach (DataRow dr in dt.Rows)
{
comboBox1.Items.Add(dr["Name"].ToString());
}
con.Close();
here is my connection string:
<add name="CafeteriaDBConnectionString"
connectionString="Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\CafeteriaDB.mdf;Integrated Security=True"
First of all, place your connection string in single location. As on connection string inside code and second in configuration file.
SqlConnection con = new SqlConnection("Data Source=.;InitialCatalog=CAFETERIADB; Integrated Security=True;");
To make it working first test your connection string.
Save notepad file as name.udl
double click and provide appropriate values if local server (pc name \SQLEXPRESS) or (.\SQLEXPRESS)
Click test and again open same udl file in notepad
copy the connection string it will be some thing like below but exclude provider part
Password=;Persist Security Info=True;User ID=;Initial Catalog=CafeteriaDB;Data Source=.\SQLEXPRESS
SqlConnection con = new SqlConnection("Password=***;Persist Security Info=True;User ID=***;Initial Catalog=CafeteriaDB;Data Source=.\SQLEXPRESS;")
I hope this will helps you.
I don't think in your code you are referring to the connection string you set up in config file. Instead, you hard-coded a new connection in the first line of your code.
If you are sure the connection string in config file works fine, you can put it into your code directly.
Change your first line code as:
SqlConnection con = new SqlConnection("Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\CafeteriaDB.mdf;Integrated Security=True");
Or you can refer to connection string in config file.
string connectionString = DatabaseHelper.CafeteriaDBConnectionString;
SqlConnection con = new SqlConnection(connectionString);

How to convert selected date to string and view on DataGrid

I'm trying to search for data between two dates and show on the datagrid. However I'm getting an error says that toString is unable to convert the selected date to string.
private void searchButton_Click(object sender, RoutedEventArgs e)
{
SqlConnection con = new SqlConnection(#"Data Source = xmsql04.australiaeast.cloudapp.azure.com,6302 ;Initial Catalog=DAD_TruckRental_RGM;Persist Security Info=True;User ID=xxxxxx;Password=xxxxxx");
SqlDataAdapter sda = new SqlDataAdapter("SELECT RentalId,TruckId,CustomerID,TotalPrice,RentDate,ReturnDueDate FROM TruckRental where JoiningDate between'"+fromText.SelectedDate.Value.ToString("MM/DD/YYYY")+"'AND'"+toText1.SelectedDate.Value.ToString("MM/DD/YYYY")+"'", con);
DataSet ds = new DataSet();
sda.Fill(ds, "TruckRental");
gridView2.ItemsSource = ds.DefaultViewManager;
}
UPDATE:
I have changed my code and have gotten rid of the error. However, no data is showing on in the grid, only an empty row. Would anyone know why that is?
string sqlStr = "SELECT RentalId,TruckId,CustomerID,TotalPrice,RentDate,ReturnDueDate FROM TruckRental where RentDate between #fromDT AND #toDT";
string connStr = #"Data Source = xmsql04.australiaeast.cloudapp.azure.com,6302 ;Initial Catalog=DAD_TruckRental_RGM;Persist Security Info=True;User ID=xxxxxx;Password=xxxxxx";
using (SqlConnection con = new SqlConnection(connStr))
using (SqlDataAdapter sda = new SqlDataAdapter(sqlStr, con))
{
sda.SelectCommand.Parameters.Add(new SqlParameter("#toDT", SqlDbType.DateTime)).Value = toText1.SelectedDate.Value;
sda.SelectCommand.Parameters.Add(new SqlParameter("#fromDT", SqlDbType.DateTime)).Value = fromText.SelectedDate.Value;
DataSet ds = new DataSet();
con.Open();
sda.Fill(ds, "TruckRental");
gridView2.ItemsSource = ds.DefaultViewManager;
}
There are some issues in your code.
Your con connection string didn't' open when you use Fill method, so you can't execute the SQL statement.
Your code has a SQL-Injection problem, I would suggest you use parameters instead of connected SQL statement string, make sure your parameter data type size as same as your table schema.
You didn't return the resource when you finish you have executed your SQL statement, I would use using statement because the purpose of Using statement is that when control will reach the end of using it will dispose that object of using block and free up memory. its purpose is not only for auto connection close, basically it will dispose of the connection object and obviously, the connection also closed due to it.
using SqlParameter class to make it.
private void searchButton_Click(object sender, RoutedEventArgs e)
{
string sqlStr = "SELECT RentalId,TruckId,CustomerID,TotalPrice,RentDate,ReturnDueDate FROM TruckRental where JoiningDate between #fromDt AND #toDt";
string connStr = #"Data Source = xmsql04.australiaeast.cloudapp.azure.com,6302 ;Initial Catalog=DAD_TruckRental_RGM;Persist Security Info=True;User ID=DDQ4_Melveena;Password=xxxxx";
using (SqlConnection con = new SqlConnection(connStr))
using (SqlDataAdapter sda = new SqlDataAdapter(sqlStr, con))
{
sda.SelectCommand.Parameters.Add(new SqlParameter("#toDt", SqlDbType.DateTime)).Value = toText1.SelectedDate.Value;
sda.SelectCommand.Parameters.Add(new SqlParameter("#fromDt", SqlDbType.DateTime)).Value = fromText.SelectedDate.Value;
DataSet ds = new DataSet();
con.Open();
sda.Fill(ds, "TruckRental");
gridView2.ItemsSource = ds.DefaultViewManager;
}
}

Show data base on Database

I have a form with ComboBox to list items name and label PRODUCTID Value to describe its item ID:
I have a class Connect to query. Here is the code:
class Connect
{
SqlConnection con;
public Connect()
{
String connectionString = #"Data Source=.\SQLEXPRESS;AttachDbFilename=" + Application.StartupPath + #"\Database1.mdf;Integrated Security=True;User Instance=True";
con = new SqlConnection(connectionString);
}
public DataTable executeSelect(String query)
{
con.Open();
SqlDataAdapter adapter = new SqlDataAdapter(query, con);
DataTable dt = new DataTable();
adapter.Fill(dt);
con.Close();
return dt;
}
public void execute(String query)
{
con.Open();
SqlCommand cmd = new SqlCommand(query, con);
cmd.ExecuteNonQuery();
con.Close();
}
}
My problems is I want my form to show its Product ID when i choose selected item in comboBox. And the data is the same with the data in database For example, I select Batman book in combo box, the label will show its Product ID and the ID must be the same in database. Could you please give me the example of code to solve this problem?? Thank you
private void cboType_SelectedIndexChanged(object sender, EventArgs e)
{
string ptype = cboType.Text.ToString().Trim();
//change query according to your db
string sql = string.Format(#"select productid from yourtable where producttype = '{0}'", ptype);
Connect con = new Connect();//you should learn ExecuteScalar method
DataTable dt = con.executeSelect(sql);
object id = dt.Rows[0][0];//assume data in db is consistent,
this.lblID.Text = id.ToString();
}

A form is loaded but how to extract data from SQL to combobox?

Still learning C#
A comboBox is created and Tables called mainCat and subCat is created.
I have a code , but i am stuck to understand on how to get the data from mainCat to the comboBox , which is then used by another comboBox for the subCat to set a subcategory.
The Get Connection is underlined red. Why?
Here is my code -
System.Data.SqlServerCe.SqlCeConnection con;
System.Data.SqlServerCe.SqlCeDataAdapter da;
DataSet ds1;
private void Form2_Load(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection();
conn.ConnectionString = "Data Source=.\\SQLEXPRESS;Initial Catalog=master;Integrated Security=True";
conn.Open();
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
using (SqlConnection Con = GetConnection())
{
SqlDataAdapter da = new SqlDataAdapter("Select Category.Category ,Category.Id from Category", Con);
SqlCommand cmd = new SqlCommand("SELECT * from MAINCAT");
DataTable dt = new DataTable();
da.Fill(dt);
mainCatU.DataSource = dt;
mainCatU.DisplayMember = "Category";
mainCatU.ValueMember = "Id";
mainCatU.Text = "<-Please select Category->";
myComboBox.DropDownStyle = ComboBoxStyle.DropDownList;
}
}
So i then i tried another code.. but still doesnt work..
public partial class User : Form
{
System.Data.SqlServerCe.SqlCeConnection con;
System.Data.SqlServerCe.SqlCeDataAdapter da;
DataSet ds1;
private void User_Load(object sender, EventArgs e)
{
con = new System.Data.SqlServerCe.SqlCeConnection();
con.ConnectionString = "Data Source=PEWPEWDIEPIE\\SQLEXPRESS;Integrated Security=True";
con.Open();
MessageBox.Show("Database connected");
ds1 = new DataSet();
string sql = "SELECT * from MAINCAT";
da = new System.Data.SqlServerCe.SqlCeDataAdapter(sql, con);
da.Fill(ds1, "SCSID");
mainCatU.DataSource = ds1;
con.Close();
mainCatU.Text = "<-Please select Category->";
mainCatU.DropDownStyle = ComboBoxStyle.DropDownList;
mainCatU.Enabled = true;
}
}
then i just used the data bound item function through the combobox GUI..
this.mAINCATTableAdapter.Fill(this.masterDataSet.MAINCAT);
but , the box didn't show any value , except "System.Data.DataRowView" in the comboBox
==================================================================================
System.Data.SqlServerCe.SqlCeConnection con; //not used at the moment
System.Data.SqlServerCe.SqlCeDataAdapter da; //not used at the moment
DataSet ds1;
private void User_Load(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection();
conn.ConnectionString = "Data Source=PEWPEWDIEPIE\\SQLEXPRESS;Initial Catalog=master;Integrated Security=True";
conn.Open();
MessageBox.Show("Database connected");
SqlDataAdapter da = new SqlDataAdapter("SELECT * from MAINCAT", conn);
ds1 = new DataSet();
da.Fill(ds1, "MainCat");
mainCatU.DisplayMember = "maincat";
mainCatU.ValueMember = "maincat";
mainCatU.DataSource = ds1.Tables["MAINCAT"];
}
===============
and the combo box is still not showing anything from the database table
You need to create the function GetConnection():
public string ConnectionString { get; set;}
public SqlConnection GetConnection()
{
SqlConnection cn = new SqlConnection(ConnectionString);
return cn;
}
TBH, unless you want to do something in GetConnection, you might be better just creating it inline:
using (SqlConnection Con = new SqlConnection(ConnectionString))
{
EDIT:
Based on your revised question, I think the problem now may be here:
mainCatU.DisplayMember = "maincat";
mainCatU.ValueMember = "maincat";
mainCatU.DataSource = ds1.Tables["MAINCAT"];
My guess is that your table structure is not maincat.maincat. The display and value members should be set to the field name that you wish to display.
I am really sorry I am a vb developer but the concept is same to populate data into combo using sql is
Declare SQLConnection Declare SQLDataReader Declare SQLCommand
Try
If Con.State = ConnectionState.Closed Then
Con.Open()
cmd.Connection = Con
cmd.CommandText = "Select field1, field2 from table"
dr = cmd.ExecuteReader()
' Fill a combo box with the datareader
Do While dr.Read = True
ComboBoxName.Items.Add(dr.GetString(0))
ComboBoxName.Items.Add(dr.GetString(1))
Loop
Con.Close()
End If
Catch ex As Exception
MsgBox(ex.Message)
End Try
Hope it works for you.

Categories