I have created a login form, which checks database for username and password you provided, and if username exists logs you in and transfer you to next form which says: "Welcome 'username' " . Now, I want to show other info from another table about the person who loggs in that are recorded in the database. Here is my code, been struggling with it, don't know what to change to make it work, I'm getting errors for cmd and reader saying that they don't exist in the current context.
private void PopulateFields()
{
string conString = (#"Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\Users\slame\OneDrive\Dokumenti\relacijska_baza_podataka.mdf;Integrated Security=True;Connect Timeout=30;");
SqlConnection con = new SqlConnection(conString);
string selectSql = "select * from Pending_Tasks";
SqlCommand com = new SqlCommand ("Select * From student where username='" + textBox3.Text + "' and Password ='" + textBox4.Text + "'", con);
try
{
con.Open();
using (SqlDataReader read = cmd.ExecuteReader())
{
while(reader.Read())
{
textBox3.Text = (read["username"].ToString());
textBox4.Text = (read["password"].ToString());
}
}
}
finally
{
con.Close();
}
Related
I want get image from API to XAMARIN I have API connected to MYSQL if I try get image he give me nothing that is the code.
API
[HttpGet]
public string Plan(string Code, string Company, string Centrale, string Zone)
{
object imag = null;
DataSet ds = new DataSet();
try
{
MySqlConnection con = new MySqlConnection(connectionDB.ConnectionString);
MySqlCommand cmd = new MySqlCommand("select imag from photo inner join taskhis on photo.company = taskhis.company and " +
" photo.zone = taskhis.zone where taskhis.codes ='" + Code + "' and taskhis.company ='" + Company + "' " +
"and taskhis.centrale = '" + Centrale + "' and taskhis.zone = '" + Zone + "' and dates ='" + DateTime.Now.ToString("yyyy/MM/dd") + "' group by taskhis.zone", con);
con.Open();
MySqlDataReader dr = cmd.ExecuteReader();
if(dr.Read())
{
imag = dr[0];
}
//MySqlDataAdapter da = new MySqlDataAdapter(cmd);
//da.Fill(ds);
dr.Close();
con.Close();
}
catch (Exception ex)
{
}
return imag.ToString() ;
}
connection method
string MainUri = "http://192.168.1.25:5873/api/C1NET/";
public async Task<string> GetRequest(string uri)
{
string Tache = "";
var client = new RestClient(MainUri);
var request = new RestRequest(uri);
var response = client.Execute(request);
return response.Content;
}
MainPage
string[] item = plan.urTask.Split(';');
VPNConnector VP = new VPNConnector();
string Result = VP.GetRequest("Plan?Code=" + item[4]+ "&Company="+item[0]+ "&Centrale="+item[1]+ "&Zone="+item[2]).Result;
byte[] image = Encoding.ASCII.GetBytes(Result);
MemoryStream ms = new MemoryStream(image);
IMAGES.Source = ImageSource.FromStream(() => ms);
please if someone can help me to fix my code that can be great thank you
How do i add data to dataGrid view in VB.net (I'm using WPF dataGrid).
Here is a code that works, this code is for login, my application can access database and i can manipulate data:
Public Function login(ByVal username As String, ByVal password As String)
Try
ManageConnection(False) 'Open connection'
Dim strQuery As String = "SELECT * FROM `dbns`.`wrks` WHERE `username` = '" + username + "' and password = '" + password + "'"
Dim SqlCmd As New MySqlCommand(strQuery, dbCon)
Dim reader As MySqlDataReader = SqlCmd.ExecuteReader()
If reader.HasRows Then
Return True
Else
Return False
End If
reader.Close()
Catch ex As MySqlException
Console.WriteLine("Error: " & ex.ToString())
Finally
ManageConnection(True)
End Try
Return False
End Function
How would i implement a SELECT * FROM xxxxx WHERE xxxx and populate
<DataGrid x:Name="dataGrid" HorizontalAlignment="Left" Margin="376,167,0,0" VerticalAlignment="Top" Height="100" Width="645"/>
This is my Sub for opening and closing connection:
Public Sub ManageConnection(ByVal CloseConnection As Boolean)
Try
'Pripremanje konekcije i upita'
dbCon = New MySqlConnection("server=127.0.0.1;user id=root;password=*****;database=****")
If CloseConnection = False Then
If dbCon.State = ConnectionState.Closed Then _
dbCon.Open()
Else
dbCon.Close()
End If
Catch ex As Exception
MsgBox("Nije moguća konekcija na udaljenu bazu podataka, koristi drugu opciju.")
End Try
End Sub
I want to know if i can use my existing function for connecting to database for datagrid specific needs.
In example:
Public Function testniQuery()
Dim queryString As String =
"SELECT * FROM table"
Dim adapter As SqlDataAdapter = New SqlDataAdapter(
queryString, connection)
Dim customers As DataSet = New DataSet
adapter.Fill(customers, "Customers")
End Function
I do not know Visual Basic that well because I work with C# but the Common Library Runtime (CLR) makes it easier to understand both languages.
When you are connected to MySQL, run your query which you will use DataAdapter to get the data from the query.
The result of the query can be saved in a DataTable and you can easily bind the DataTable to the DataGrid.
So, you run one query and you can use that table persistently in your code.
I do this is C#.
Please bear with C# code. This is a method that will do it
public DataTable Login(string username, string password){
//"SELECT * FROM `dbns`.`wrks` WHERE `username` = '" + username + "' and password = '" + password + "'"
string query = "SELECT * FROM wrks WHERE username = #username AND password = #password";
DataTable table = new DataTable();
using (MySQlConnection connection = new MySQlConnection(connectionString))
{
using (MySqlDataAdapter adapter = new MySqlDataAdapter(query, connection))
{
adapter.SelectCommand.Parameters.AddWithValue("#username", username);
adapter.SelectCommand.Parameters.AddWithValue("#password", password);
adapter.Fill(table);
return table;
}
}
}
The DataTable returned can then be binded to the DataGrid as shown below:
dataGrid1.DataSource = Login("username", "password").DefaultView;
dataGrid1.DataBind();
I have two tables in the database:
Login (LID,UName,UPasword,UserType_ID)
UserType(UserType_ID,UserType)
I need to validate username and usertype and create a session variable for UserName(UName).
Below is the code which I try but it shows me error
Error 58 The type or namespace name 'UserInformation' could not be found (are you missing a using directive or an assembly reference?)
CODE
public string LogOn(UserInformation objLogOnUserInformation)
{
// ConnectionManager conCm = new ConnectionManager();
try
{
MySqlConnection con = conn.Open();
MySqlCommand cmd, cmdOne;
MySqlDataReader dr;
// SqlDataReader dr;
string _str = "U";
cmd = new MySqlCommand("select LID from Credentials", con);
dr = cmd.ExecuteReader();
while (dr.Read())
{
//checking user name is present in database
if (dr.GetValue(0).ToString() == objLogOnUserInformation.UserId)
{
dr.Close();
//retriving Password for the existing user
cmd = new MySqlCommand("select Pasword from login where LID='" + objLogOnUserInformation.UserId + "'", con);
dr = cmd.ExecuteReader();
while (dr.Read())
{
//checking the password is matching with the database
if (dr.GetValue(0).ToString() == objLogOnUserInformation.Password)
{
dr.Close();
cmd = new MySqlCommand("select UserType_ID from login where LID='" + objLogOnUserInformation.UserId + "'", con);
dr = cmd.ExecuteReader();
while (dr.Read())
{
//checking user type
if (dr.GetValue(0).ToString() == _str)
{
dr.Close();
cmdOne = new MySqlCommand("select UName from login where LID='" + objLogOnUserInformation.UserId + "'", con);
dr = cmdOne.ExecuteReader();
dr.Read();
objLogOnUserInformation.SessionUserName = dr.GetValue(0).ToString();
dr.Close();
//if usertype is customer, U is returned
Response.Redirect("gallery.aspx");
}
else
{
dr.Close();
cmdOne = new MySqlCommand("select UName from login where LID='" + objLogOnUserInformation.UserId + "'", con);
dr = cmdOne.ExecuteReader();
dr.Read();
objLogOnUserInformation.SessionUserName = dr.GetValue(0).ToString();
dr.Close();
//If usertype is Admin, A is returned
Response.Redirect("Reports.aspx");
}
}
}
else
{
return " Either User Name or Password is not Valid";
}
}
}
}
}
catch
{
}
}
i try to build signup code using asp.net and mysql
code is
protected void Button2_Click(object sender, EventArgs e)
{
try
{
string MyConnection2 = "Server=xxx; Port=3306 ; Uid=xxx; pwd=xxx;Database=maintainance";
string Query = "INSERT INTO `login`(`UName`, `UPasword`,`UserTypeID`,`Email`)VALUES('" + this.TextBox1.Text + "','" + this.TextBox2.Text + this.DropDownList1.SelectedValue +this.TextBox3.Text+ "');";
MySqlConnection MyConn2 = new MySqlConnection(MyConnection2);
MySqlCommand MyCommand2 = new MySqlCommand(Query, MyConn2);
MySqlDataReader MyReader2;
MyConn2.Open();
MyReader2 = MyCommand2.ExecuteReader();
Label3.Text = ("Your Data saved successfully");
while (MyReader2.Read())
{
}
MyConn2.Close();
}
catch
{
Label3.Text = ("Data saved failed");
}
}
but it shows me Data saved failed ... where is the error and how i correct this?
You have to pass value according to column before VALUES
string Query = "INSERT INTO `login`(`UName`, `UPasword`,`UserTypeID`,`Email`) VALUES ('" + this.TextBox1.Text + "','" + this.TextBox2.Text+"', '"+this.DropDownList1.SelectedValue+"' ,'"+this.TextBox3.Text+ "');";
I'm trying to add titles (picture) from all rows to a listbox and I'm getting this error:
An unhandled exception of type 'System.IndexOutOfRangeException' occurred in System.Data.dll. Not sure what to do at this point I've tried adding functions, making it a variable called item..
Public Function updatenews()
Dim MySqlConnection As New MySqlConnection()
Dim newsmydatatable As New DataTable
Dim rowcount As Integer = 0
Dim amount As Integer
MySqlConnection.ConnectionString = "server=" + host + "; user id=" + user + "; password=" + password + "; database=website;"
Try
MySqlConnection.Open()
Catch myerror As MySqlException
MessageBox.Show("Cannot connect news server: " & myerror.Message & "Please check your internet connection settings and try again. If problem persists contact support.")
Label3.Text = "Error!"
End Try
Dim myadapter As New MySqlDataAdapter
Dim newsmydatatable As New DataTable
Dim sqlquary = "SELECT * FROM news;"
Dim command As New MySqlCommand
command.Connection = MySqlConnection
command.CommandText = sqlquary
myadapter.SelectCommand = command
myadapter.Fill(newsmydatatable)
Dim mydata As MySqlDataReader
mydata = command.ExecuteReader()
If mydata.HasRows = 0 Then
Else
amount = newsmydatatable.Rows.Count
MsgBox(amount)
For value As Integer = 0 To amount
For value As Integer = 0 To amount
ListBox1.Items.Add(newsmydatatable.Rows(rowcount).Item("title"))
rowcount += 1
Next
End If
End Function
where you have:
ListBox1.Items.Add(newsmydatatable.Rows(rowcount).Item("title"))
rowcount += 1
change it to:
ListBox1.Items.Add(newsmydatatable.Rows(value).Item("title"))