I have some code here that connects to my Mysql database. It checks your username and password and if your login was successful and it retrieves the phone number under that account. How would the SQL Query look like for retrieving the phone number once connected? Then how would I be able to display that phone number on a label?
Have a look at this tutorial, should cover most of what you would need to know about connecting to MySQL, executing queries and displaying results:
VBMySQL Tutorial - Part 4
There are a number of other tutorials on that site, should get you going.
If part 4 gets into too much depth too quickly, check out part 1 first
public partial class _Default : System.Web.UI.Page
{
string strCon = ConfigurationManager.AppSettings["myConString"];
SqlConnection con;
SqlCommand com;
public string strPKDataValue;
public SqlDataReader dr;
protected void Page_Load(object sender, EventArgs e)
{
con = new SqlConnection(strCon);
}
protected void Button5_Click(object sender, EventArgs e)
{
com = new SqlCommand("select * from student", con);
con.Open();
try
{
dr = com.ExecuteReader(CommandBehavior.CloseConnection);
if (dr.HasRows)
{
if (dr.Read())
{
Label9.Text = Convert.ToString(dr["stuid"]);
}
}
}
catch (Exception ex)
{
Response.Write("Error :" + ex.Message);
}
finally
{
dr.Close();
con.Close();
}
}
}
Related
I have a multi-select control whereby I need to commit all items selected to SQL Server table. When I submit the form only 1 item is getting committed even though when i inspect using Step Debugger all the selected values are indeed populated in variable employeees4 (attached image). i have observed that only the first item in the selection is getting committed. Any help on what i could possibly be missing?
Please note that i have used slightly different variable name in attached image has i.e year instead of employeees4, but the code is the same .
I am getting selected items as below :
[HttpPost]
public ActionResult NewOverTimeRequest(FormCollection formcollection)
{
Models.Employee.OverTimeRequest request = new Models.Employee.OverTimeRequest();
try
{
var batch = new OvertimeBatch();
request.employees = GetEmployees();
request.EmployeeNumber = new string[] { Convert.ToString(formcollection["EmployeeNumber"]) };
var employeees1= request.EmployeeNumber.Split(',');
string[] employeees2 = employeees.SingleOrDefault().ToArray();
string employeees3 = Helpers.ConvertStringArrayToString( employeees2);
string[] employeees4 =employeees3.Split(new char[] { ',' });
if (ModelState.IsValid)
{
foreach ( string emp in employeees4)
{
using (SqlConnection conn = new SqlConnection(Helpers.DatabaseConnect))
{
SqlCommand cmd = new SqlCommand("SubmitOverTime", conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#EmpNum", emp);
cmd.Parameters.AddWithValue("#DateDone", DateTime.Now);
conn.Open();
cmd.ExecuteNonQuery();
}
}
return RedirectToAction("OverTime");
}
catch (Exception ex)
{
ViewBag.ErrorMessage = ex.Message;
return View(request);
}
return RedirectToAction("OverTime");
}
}
Model :
[Required]
[Display(Name = "Employee ")]
public string[] EmployeeNumber { get; set; }
public Employee Employee { get; set; }
public String DisplayName { get; set; }
public IEnumerable<SelectListItem> employees { get; set; }
Try changing you If condition to below.
if (ModelState.IsValid)
{
using(SqlConnection conn = New SqlConnection(Helpers.DatabaseConnect))
{
conn.Open();
SqlCommand cmd = New SqlCommand("SubmitOverTime", conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#EmpNum", SqlDbType.varchar(max));
cmd.Parameters.Add("#DateDone", SqlDbType.DateTime);
foreach(String emp In employeees4)
{
cmd.Parameters["#FixtureId"].Value=emp;
cmd.Parameters["#FixtureId"].Value= DateTime.Now;
cmd.ExecuteNonQuery();
}
}
return RedirectToAction("OverTime");
}
I'm developing windows phone 8 application.
I'm having some difficulty with my sqlite prepare statement. I get an error saying my table does not exist, although I've checked in multiple places for it, and it does exist.
It did work until I added some new tables to the SQLite database and now it just doesn't recognise any of the tables - so I'm confused!
I have also tried hardcoding the full path.. e.g. C:\App\datbase.db etc
Code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using System.IO.IsolatedStorage;
using SQLitePCL;
namespace WP7.VideoScanZXing.SampleApp
{
public partial class Page1 : PhoneApplicationPage
{
string connLOCDAT = "Data Source =\\Resources\\DB\\MCRS_Data.sdf;Persist Security Info=False";
string connLOCLUDAT = "Data Source =\\Resources\\DB\\MCRSLU_MYCUBE.sdf;Persist Security Info=False";
public Page1()
{
InitializeComponent();
//check the isolated storage to see if the user has saved a username and password.
CheckIsoStore();
}
public void CheckIsoStore() {
if (IsolatedStorageSettings.ApplicationSettings.Contains("UsrEmail"))
{
//The user has saved details
//populate the email and password box automatically
//Dont forget to check the save details box too
tbEmail.Text = IsolatedStorageSettings.ApplicationSettings["UsrEmail"].ToString();
pbPassword.Password = IsolatedStorageSettings.ApplicationSettings["UsrPassword"].ToString();
cbSaveDetails.IsChecked = true;
}
}
public void failedLogin()
{
MessageBox.Show("Error: Email or Password are incorrect. Please try again.");
tbEmail.Focus();
}
private void btnLogin_Click(object sender, RoutedEventArgs e)
{
//validate user
string strEmail = tbEmail.Text;
string strPassword = pbPassword.Password.ToString();
//bool bolValidUser = false;
//validate username and password here!
if (bolValidUser(strEmail, strPassword) == true)
{
//user has been validated and can continue.
if (cbSaveDetails.IsChecked == true)
{
//save the users details here
IsolatedStorageSettings.ApplicationSettings["UsrEmail"] = strEmail;
IsolatedStorageSettings.ApplicationSettings["UsrPassword"] = strPassword;
IsolatedStorageSettings.ApplicationSettings.Save();
}
else {
IsolatedStorageSettings.ApplicationSettings.Remove("UsrEmail");
IsolatedStorageSettings.ApplicationSettings.Remove("UsrPassword");
IsolatedStorageSettings.ApplicationSettings.Save();
}
NavigationService.Navigate(new Uri("/MenuPage.xaml", UriKind.Relative));
}
else {
//redirect the user back to the home screen with a message
//NavigationService.Navigate(new Uri("/LoginPage.xaml?message=Login error ", UriKind.Relative));
failedLogin();
}
}
public static SQLiteConnection dbConn;
public bool bolValidUser(string Uname, string PWord)
{
dbConn = new SQLitePCL.SQLiteConnection(Windows.ApplicationModel.Package.Current.InstalledLocation.Path + #"\bizData.db", SQLiteOpen.READWRITE);
{
//StorageFile databaseFile = await .GetFileAsync("bizData.db");
//await databaseFile.CopyAsync(ApplicationData.Current.LocalFolder);
}
//using (var statement = dbConn.Prepare(#"SELECT * FROM [MCRS_LU_Login] WHERE [Email] = " + Uname + " AND [Password] = " + PWord))
using (var statement = dbConn.Prepare(#"SELECT * FROM [BARCODES]"))
{
if (statement.Step() == SQLiteResult.ROW)
{
//new MessageDialog(Convert.ToString(statement.DataCount)).ShowAsync();
//if ()
string strLinkedUser;
strLinkedUser = statement[3].ToString();
IsolatedStorageSettings.ApplicationSettings["UsrADName"] = statement[0].ToString();
return true;
}
else
{
return false;
//await msgDialog.ShowAsync();
}
}
}
private void tbEmail_GotFocus(object sender, RoutedEventArgs e)
{
imgMail.Visibility = Visibility.Collapsed;
}
private void tbEmail_LostFocus(object sender, RoutedEventArgs e)
{
if(tbEmail.Text =="") {
imgMail.Visibility = Visibility.Visible;
}
}
private void pbPassword_LostFocus(object sender, RoutedEventArgs e)
{
if (pbPassword.Password == "")
{
imgPassword.Visibility = Visibility.Visible;
}
}
private void pbPassword_GotFocus(object sender, RoutedEventArgs e)
{
imgPassword.Visibility = Visibility.Collapsed;
}
}
}
is there a way of randomizing the user agent using Gecko Browser ? i tried doing it on a separated thread but i couldn't since Gecko must be ran on the same Thread.
try this
Create new class Global.cs
public class Globals
{
public static ArrayList Useragent = new ArrayList();
}
next in your form1 code
private string GetUserAgent()
{
Random Rnd = new Random();
return Convert.ToString(Globals.Useragent[Rnd.Next(0, Globals.Useragent.Count)]);
}
load your file with user agent lines
private void button2_Click(object sender, EventArgs e)
{
var OpenFile = new OpenFileDialog();
OpenFile.Filter = "*.txt | *.txt";
OpenFile.ShowDialog();
if (OpenFile.FileName != "")
{
Globals.Useragent.AddRange(File.ReadAllLines(OpenFile.FileName));
}
else
{
MessageBox.Show("Chooee Your User agent file");
}
}
======================
private string GetUserAgent()
{
Random Rnd = new Random();
return Convert.ToString(Globals.Useragent[Rnd.Next(0, Globals.Useragent.Count)]);
}
Ok its finish!
Now you can do this - input your new code GetUserAgent();
private void button1_Click(object sender, EventArgs e)
{
CookieManager.RemoveAll();
Gecko.GeckoPreferences.User["general.useragent.override"] = GetUserAgent();
}
Hi i am trying to implement sqldependancy with signalr for new database changes. but the problem is if i edit only one row then also sqldependancy is firing more time. and some time it is not firing. I have web application without MVC. bellow is my code
public void page_load(object sender, EventArgs e)
{
//notification.GetAllUnreadSalesNotifications();
NewScrapNotifications();
}
public void NewScrapNotifications()
{
string message = string.Empty;
using (SqlConnection connection = new SqlConnection(IFTDAL.IFTCommon.DSN))
{
string query = "SELECT [Message] FROM [dbo].[DummyData]";
using (SqlCommand command = new SqlCommand(query, connection))
{
command.Notification = null;
SqlDependency dependency = new SqlDependency(command);
dependency.OnChange += new OnChangeEventHandler(dependency_OnChange);
connection.Open();
SqlDataReader reader = command.ExecuteReader();
if (reader.HasRows)
{
reader.Read();
message = reader[0].ToString();
}
}
}
}
private void dependency_OnChange(object sender, SqlNotificationEventArgs e)
{
if (e.Type == SqlNotificationType.Change)
{
IFTHub nHub = new IFTHub();
nHub.NotfiyAllClients();
// NewScrapNotifications();
//LoadDashboardByDashboardViewID(1);
}
}
and I also have bellow code in Globa.asax
void Application_Start(object sender, EventArgs e)
{
// Code that runs on application startup
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
SqlDependency.Start(DAL.DSN);
}
protected void Application_End(object sender, EventArgs e)
{
SqlDependency.Stop(DAL.DSN);
}
You are creating new SQLDependency on each page load (refresh). I bet there is correlation between number of page reloads and number of notifications page is receiving via SignalR.
Register your notification only once per app lifetime...
I am creating a REST Web Service using Java and Jersey API. The basic REST service works fine,but when I add in a DB connection it gives me a Class Not Found Exception and a SQL Exception - No driver found. I have included the ojdbc6.jar file in the Eclipse build path. Using the same code if I create a Java application it runs fine.
I have added my code below. Can some one plz suggest something.
EDIT: I included the jar file in the WEB-INF lib directory. But when I try to execute the code I get the following error: HTTP Status 405 - Method Not Allowed
public class Note {
private int noteId;
private String content;
private Date createdDate;
public Note() {}
public Note(int noteId, String content, Date createdDate) {
this.noteId = noteId;
this.content = content;
this.createdDate = createdDate;
}
public int getNoteId() {
return noteId;
}
public void setNoteId(int noteId) {
this.noteId = noteId;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public Date getCreatedDate() {
return createdDate;
}
public void setCreatedDate(Date createdDate) {
this.createdDate = createdDate;
}
#Override
public String toString() {
return "Note [content=" + content + ", createdDate=" + createdDate
+ ", noteId=" + noteId + "]";
}
}
public class NoteDAO {
DatabaseAccess data;
Connection connection;
public NoteDAO()
{
try {
data = new DatabaseAccess();
connect();
} catch (SQLException e) {
e.printStackTrace();
}
}
private void connect() throws SQLException
{
try
{
data.connect();
connection = data.connection;
}
catch (SQLException e)
{
e.printStackTrace();
}
}
public Note getNoteById(int id)
{
PreparedStatement prepStmt = null;
try {
String cSQL = "SELECT * FROM NOTE WHERE NOTEID = 12 ";
prepStmt = connection.prepareStatement(cSQL);
prepStmt.setInt(1, id);
ResultSet result = prepStmt.executeQuery();
Note note = new Note();
while (result.next())
{
note.setNoteId(result.getInt(1));
note.setContent(result.getString(2));
note.setCreatedDate( (Date) new java.util.Date(result.getDate(3).getTime()));
}
return note;
} catch (SQLException e) {
e.printStackTrace();
prepStmt = null;
return null;
}
}
}
#Path("/notes")
public class Notes {
#Context
UriInfo uriInfo;
#Context
Request request;
NoteDAO dao = new NoteDAO();
#Path("{note}")
#GET
#Produces(MediaType.APPLICATION_XML)
public Note getNote(
#PathParam("note") String idStr) {
int id = Integer.parseInt(idStr);
Note note = dao.getNoteById(id);
if(note==null)
throw new RuntimeException("Get: Note with " + id + " not found");
return note;
}
public class DatabaseAccess {
Connection connection = null;
public void connect() throws SQLException
{
String DRIVER = "oracle.jdbc.driver.OracleDriver";
String URL = "jdbc:oracle:thin:#xx.xxx.xx.xxx:1521:XXXX";
String UserName = "username";
String Password = "password";
try
{
Class.forName(DRIVER);
}
catch (ClassNotFoundException e)
{
e.printStackTrace();
}
try
{
connection = DriverManager.getConnection(URL,UserName,Password);
}
catch (SQLException e)
{
e.printStackTrace();
}
}
public void disconnect() throws SQLException
{
connection.close();
}
}
If you are using datasources that are managed by the application server, you need to put the ojdbc6.jar library inside the lib folder of your application server.
On JBoss for example, it would be $JBOSS_HOME/server/default/lib.
This is required, because in such case, the datasource is being build when the server starts and independently from your application, which means the server cannot use your application JARs.
If, however, you are pooling the connections yourself, you need to make sure, that the ojdbc6.jar is inside the lib folder of your application WAR archive.