If I want to connect to the database it crashes? - mysql

using System;
using Xamarin.Forms;
using UIKit;
using MySql.Data.MySqlClient;
namespace test.project
{
public partial class ViewController : UIViewController
{
partial void UIButton197_TouchUpInside(UIButton sender)
{
if (textBoxName.Text == "" || textBoxpasswd.Text == "")
{
var alert = UIAlertController.Create("Fehler", "Bitte geben sie Benutzername und Password ein", UIAlertControllerStyle.Alert);
alert.AddAction(UIAlertAction.Create("Ok", UIAlertActionStyle.Default, null));
PresentViewController(alert, true, null);
// Fehlerüberprüfung wenn leer ist
}
else
{
try
{
MySqlConnection con = new MySqlConnection("Server=localhost;Port=8889;database=app;User Id=root;Password=;charset=utf8");
if (con.State == System.Data.ConnectionState.Closed)
{
con.Open();
MySqlCommand cmd = new MySqlCommand("INSERT INTO users(id, username, passwd, rank) VALUES(#user, #pass, #rank)", con);
cmd.Parameters.AddWithValue("#user", textBoxName.Text);
cmd.Parameters.AddWithValue("#pass", textBoxpasswd.Text);
cmd.Parameters.AddWithValue("#rank", 0);
cmd.ExecuteNonQuery();
errorLabel.Text = "ausgeführt";
}
else
{
errorLabel.Text = "no connection";
}
}
catch
{
errorLabel.Text = "catch";
}
}
}
protected ViewController(IntPtr handle) : base(handle)
{
// Note: this .ctor should not contain any initialization logic.
}
public override void ViewDidLoad()
{
base.ViewDidLoad();
// Perform any additional setup after loading the view, typically from a nib.
}
public override void DidReceiveMemoryWarning()
{
base.DidReceiveMemoryWarning();
// Release any cached data, images, etc that aren't in use.
}
}
}
I try to. connect to the the Database but afte the line con.open the Programm crashes

There is obviously an issue with establishing a connection to the database.
You have defined the server as: Server=localhost
Is this absolutely correct? I highly doubt that you are running a full MySQL server on the device itself? If you are running the server on the device, is the server process running?
What is the execption that the application closes with?
CONNECTION_TIMEOUT? Probably a firewall issue
CONNECTION_REFUSED? The MySQL server process is not running.
You should also design your application to be hardened against database failures, maybe wrapping the connection with a try:
try {
connection.open();
} catch (Exception e) {
// TODO handle the connection error properly
System.err.println("An error has occurred.");
e.printStackTrace();
}

Related

Connecting to my online mysql database (phpmyadmin)

I really need your help guys .... I am trying to make a java program connects to mysql database, and I used to connect with localhost by xampp and its working fine with this code ...
public class myConnection {
public static Connection getconnection(){
Connection con = null;
try {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost/test?serverTimezone=Turkey","root","");
} catch (Exception e) {
System.out.println(e.getMessage());
}
return con;
}
}
but now I just bought an online server and made a new datebase Inside it but I have no Idea how to connect my program with it I tried a lot and I searched for many hours but I couldnt find anything about that... this is my database
and this is the code I am trying to use but I always get Communications link failure ..
public static Connection getconnection(){
Connection con = null;
try {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://mysql.bravehost.com/afkodb_3483514","username","password");
} catch (Exception e) {
System.out.println(e.getMessage());
}
return con;
}

Why JavaFX stucks when running a process?

I am building an application using JavaFX. Application does some CRUD operations with the MySQL Database. So currently, I have 2 functions.
User Registration.
Email Validation (Check if email already exists in the database).
User registration is called in a JFoenix Button event. When it clicked it is calling separate 3 functions in another class as follows,
public static int insertUser(User user) {
int status = 0;
try {
Connection con = DbConnection.getConnection();
PreparedStatement ps = con.prepareStatement("INSERT INTO users (name, password, email, country) VALUES (?, ?, ?, ?)");
ps.setString(1, user.getName());
ps.setString(2, user.getPassword());
ps.setString(3, user.getEmail());
ps.setString(4, user.getCountry());
status = ps.executeUpdate();
con.close();
}catch(Exception ex) {
ex.printStackTrace();
}
return status;
}
public static int updateTime(String email, String timestamp) {
int status = 0;
try {
Connection con = DbConnection.getConnection();
PreparedStatement ps = con.prepareStatement("UPDATE users SET timestamp = ? WHERE email = ?");
ps.setString(1, timestamp);
ps.setString(2, email);
status = ps.executeUpdate();
con.close();
}catch(Exception ex) {
ex.printStackTrace();
}
return status;
}
The problem is when I click the Button I see it is getting stuck while running that process. So I put that code inside the following,
Platform.runLater(() -> {
try {
} catch (Exception ex) {
Exceptions.printStackTrace(ex);
}
});
Now it is somewhat okay but I see it is getting a little stuck after clicking (Ripple effect is not working well and also the mouse hover effect is not working as usual).
And Email Validation is done when the user types an email in the text field and the key released event is triggered and it is checking for the database result. The code for checking email is as follows,
public static boolean emailAvailability(String email) {
boolean status = false;
try {
Connection con = DbConnection.getConnection();
PreparedStatement ps = con.prepareStatement("SELECT email FROM users WHERE email = ?");
ps.setString(1, email);
ResultSet rs = ps.executeQuery();
status = rs.next();
con.close();
}catch(Exception ex) {
ex.printStackTrace();
}
return status;
}
In the key event also it is getting stuck more. Can't type a character for some milliseconds.
I don't see any issue with my code because I have done this many times with Java Swing and all are perfectly working fine in Swing. And if a button is getting stuck with the running process I just put those codes inside the following and it works perfect,
new Thread(new Runnable() {
public void run() {
}
}).start();
I am not going to or trying to compare Java Swing and JavaFX But I need to know why JavaFX is behaving like this? What should I do to avoid this and run the program smoothly with the CSS effects if it is a huge process or not? Really appreciate it if anybody can help me. Thanks in advance.
UPDATE
Here is my signUp code. Executes when button clicks,
private void signUp(ActionEvent event) {
if (name.getText.equals("") && name.getText().isEmpty()) {
if (!name.getStyleClass().contains("error-class")) {
name.getStyleClass().add("error-class");
nameImageValidation.setImage(new Image("danger.png"));
nameImageValidation.setVisible(true);
}
} else {
name.getStyleClass().removeIf(style -> style.equals("error-class"));
nameImageValidation.setVisible(false);
}
if (password.getText.equals("") && password.getText().isEmpty()) {
if (!password.getStyleClass().contains("error-class")) {
password.getStyleClass().add("error-class");
passwordImageValidation.setImage(new Image("danger.png"));
passwordImageValidation.setVisible(false);
}
} else {
password.getStyleClass().removeIf(style -> style.equals("error-class"));
passwordImageValidation.setVisible(false);
}
if (email.getText.equals("") && email.getText().isEmpty()) {
if (!email.getStyleClass().contains("error-class")) {
email.getStyleClass().add("error-class");
emailImageValidation.setImage(new Image("danger.png"));
emailImageValidation.setVisible(false);
}
} else {
email.getStyleClass().removeIf(style -> style.equals("error-class"));
emailImageValidation.setVisible(false);
}
if (country.getText.equals("") && country.getText().isEmpty()) {
if (!country.getStyleClass().contains("error-class")) {
country.getStyleClass().add("error-class");
countryImageValidation.setImage(new Image("danger.png"));
countryImageValidation.setVisible(false);
}
} else {
country.getStyleClass().removeIf(style -> style.equals("error-class"));
countryImageValidation.setVisible(false);
}
if(emailValidation() && passwordValidation() && fieldsValidation()) {
User user = new User(name.getText(), email.getText(), password.getText(), country.getText());
int insertStatus = UserController.insertUser(user);
Timestamp timestamp = new Timestamp(System.currentTimeMillis());
if (insertStatus > 0) {
int updateStatus = UserController.updateTime(email.getText(), timestamp.toString());
if(updateStatus > 0) {
// Go to Login Page
} else {
showAlert(); // Error Message
}
} else {
showAlert(); // Error Message
}
} else {
showAlert(); // Error Message
}
}
Here the validateEmail code. Executes when user typing the email. Triggered when Key Released and when performing this after type a character have to wait some time and then appear next character and go...
private void validateEmail(KeyEvent event) {
boolean status = UserController.emailAvailability(email.getText());
if (!status) {
email.getStyleClass().removeIf(style -> style.equals("success-class"));
emailImageValidation.setImage(new Image("safe.png"));
emailImageValidation.setVisible(true);
} else {
email.getStyleClass().removeIf(style -> style.equals("error-class"));
emailImageValidation.setImage(new Image("danger.png"));
emailImageValidation.setVisible(true);
}
}
When you trigger a function from the GUI, execution happens in the main thread. Now, these calls are blocking, which means that until they return, the main thread can't update the GUI.
There are generally two ways to solve this:
Async functions, that yield (allows other code to run) until the resource they are waiting for become available
Threads, which means running part of the program in parrallel, which most likely will require you to think about locks etc.
I suggest you look into these two things, as they are quite central to making good apps that are connected to other services and IO

MySQL connection pooling with JERSEY

I'm developping a RESTful API with Jersey and MySQL.
I'm actually using the JDBC driver to connect to the database and I create a new connection everytime I want to acess it. As it clearly is a memory leakage, I started to implement the ServletContextClassclass but I don't know how to call the method when I need to get the result of a SQL query.
Here is how I did it wrong:
DbConnection.java
public class DbConnection {
public Connection getConnection() throws Exception {
try {
String connectionURL = "jdbc:mysql://root:port/path";
Connection connection = null;
Class.forName("com.mysql.jdbc.Driver").newInstance();
connection = DriverManager.getConnection(connectionURL, "root", "password");
return connection;
}
catch (SQLException e) {
throw e;
}
}
}
DbData.java
public ArrayList<Product> getAllProducts(Connection connection) throws Exception {
ArrayList<Product> productList = new ArrayList<Product>();
try {
PreparedStatement ps = connection.prepareStatement("SELECT id, name FROM product");
ResultSet rs = ps.executeQuery();
while (rs.next()) {
Product product = new Product();
product.setId(rs.getInt("id"));
product.setName(rs.getString("name"));
productList.add(product);
}
return productList;
} catch (Exception e) {
throw e;
}
}
Resource.java
#GET
#Path("task/{taskId}")
#Consumes(MediaType.APPLICATION_JSON)
public Response getInfos(#PathParam("taskId") int taskId) throws Exception {
try {
DbConnection database= new DbConnection();
Connection connection = database.getConnection();
Task task = new Task();
DbData dbData = new DbData();
task = dbData.getTask(connection, taskId);
return Response.status(200).entity(task).build();
} catch (Exception e) {
throw e;
}
}
Here is where I ended up trying to implement the new class:
ServletContextClass.java
public class ServletContextClass implements ServletContextListener {
public Connection getConnection() throws Exception {
try {
String connectionURL = "jdbc:mysql://root:port/path";
Connection connection = null;
Class.forName("com.mysql.jdbc.Driver").newInstance();
connection = DriverManager.getConnection(connectionURL, "root", "password");
return connection;
} catch (SQLException e) {
throw e;
}
}
public void contextInitialized(ServletContextEvent arg0) {
System.out.println("ServletContextListener started");
DbConnection database = new DbConnection();
try {
Connection connection = database.getConnection();
} catch (Exception e) {
e.printStackTrace();
}
}
public void contextDestroyed(ServletContextEvent arg0) {
System.out.println("ServletContextListener destroyed");
//con.close ();
}
}
But problem is, I don't know what to do next. Any help? Thanks
You need to set the Connection variable as an attribute of the ServletContext. Also, I would recommend using connection as a static class variable so you can close it in the contextDestroyed method.
You can retrieve the connection attribute in any of your servlets later on for doing your DB operations.
public class ServletContextClass implements ServletContextListener {
public static Connection connection;
public Connection getConnection(){
try {
String connectionURL = "jdbc:mysql://root:port/path";
Class.forName("com.mysql.jdbc.Driver").newInstance();
connection = DriverManager.getConnection(connectionURL, "root", "password");
} catch (SQLException e) {
// Do something
}
}
public void contextInitialized(ServletContextEvent arg0) {
System.out.println("ServletContextListener started");
getConnection();
arg0.getServletContext().setAttribute("connection", connection);
}
public void contextDestroyed(ServletContextEvent arg0) {
System.out.println("ServletContextListener destroyed");
try{
if(connection != null){
connection.close();
}
}catch(SQLException se){
// Do something
}
}
}
Finally access your connection attribute inside your Servlet (Resource). Make sure you pass #Context ServletContext to your Response method so you can access your context attributes.
#GET
#Path("task/{taskId}")
#Consumes(MediaType.APPLICATION_JSON)
public Response getInfos(#PathParam("taskId") int taskId, #Context ServletContext context) throws Exception {
try {
Connection connection = (Connection) context.getAttribute("connection");
Task task = new Task();
DbData dbData = new DbData();
task = dbData.getTask(connection, taskId);
return Response.status(200).entity(task).build();
} catch (Exception e) {
throw e;
}
}
Now that we have solved your current issue, we need to know what can go wrong with this approach.
Firstly, you are only creating one connection object which will be used everywhere. Imagine multiple users simultaneously accessing your API, the single connection will be shared among all of them which will slow down your response time.
Secondly, your connection to DB will die after sitting idle for a while (unless you configure MySql server not to kill idle connections which is not a good idea), and when you try to access it, you will get SQLExceptions thrown all over. This can be solved inside your servlet, you can check if your connection is dead, create it again, and then update the context attribute.
The best way to go about your Mysql Connection Pool will be to use a JNDI resource. You can create a pool of connections which will be managed by your servlet container. You can configure the pool to recreate connections if they go dead after sitting idle. If you are using Tomcat as your Servlet Container, you can check this short tutorial to get started with understanding the JNDI connection pool.

Reading data from Arduino Bluetooth on Windows Phone 8.1

I am developing a code that will allow me to send small amounts of data between my arduino mega and my windows 8.1 phone using a HC-05 bluetooth module.
Sending data from the phone to the arduino was pretty simple, but I am having a dire time attempting to read data that comes back from the arduino that I send on the serial port.
For testing purposes my code is simple, sending ascii charaters 'a' & 'b' to turn an LED on & off, this could not work any better, but I am having trouble trying to figure out how to correctly read the data that I send back to my phone.
I send a single arbitrary ascii character back to the phone but I cannot for the life of me figure out the correct way of reading this data from the bluetooth stream I have setup.
I have been trying for nearly two days, but everything I try ends up freezing my phone with no exceptions thrown? A lot of posts online send me to the Nokia dev site which is now inactive.
I have tried using the 'datareader' and the 'streamreader' classes to do this but it always freezes, does anyone know how to make this work? And why my streamreader keeps freezing my phone?
I have tried to annotate my code appropriatley (seen below). The problem occurs in the 'Tick' event handler at the bottom of the code.
(FYI: All capabilities have been added to the manifest files so this shouldn't be the problem).
Thank you.
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 Bluetooth_SL.Resources;
using Windows.Networking;
using Windows.Networking.Proximity;
using Windows.Networking.Sockets;
using Windows.Devices.Bluetooth;
using System.IO;
using Microsoft.Xna.Framework;
using System.Windows.Threading;
using Windows.Storage.Streams; // <-- for the datareader class
namespace Bluetooth_SL // silverlight, does this matter?
{
public partial class MainPage : PhoneApplicationPage
{
DispatcherTimer Timer = new DispatcherTimer();
StreamSocket socket = new StreamSocket();
StreamWriter writer;
StreamReader reader;
public MainPage()
{
InitializeComponent();
Timer.Interval = TimeSpan.FromMilliseconds(1000); // dispatcher timer used to check for incoming data from arduino
Timer.Tick += Timer_Tick; // event handler for dispatcher timer
}
protected override void OnNavigatedFrom(NavigationEventArgs e) // frees up memory
{
socket.Dispose();
}
private void Connect_But_Tap(object sender, System.Windows.Input.GestureEventArgs e)
{
ConnectToBluetooth();
}
private async void ConnectToBluetooth() // sets up the connection // this works fine
{
// Configure PeerFinder to search for all paired devices.
PeerFinder.AlternateIdentities["Bluetooth:Paired"] = "";
var pairedDevices = await PeerFinder.FindAllPeersAsync();
if (pairedDevices.Count == 0)
{
Debug_Block.Text = "No paired devices were found.";
}
else
{
Debug_Block.Text = "Found";
PeerInformation selectedDevice = pairedDevices[0]; // pick the first paired device
try // 'try' used in the case the socket has already been connected
{
await socket.ConnectAsync(selectedDevice.HostName, "1");
writer = new StreamWriter(socket.OutputStream.AsStreamForWrite());
writer.AutoFlush = true;
reader = new StreamReader(socket.InputStream.AsStreamForRead());
Debug_Block.Text = "Connected";
}
catch (Exception x)
{
Debug_Block.Text = x.ToString();
}
}
}
private void SendButton_Tap(object sender, System.Windows.Input.GestureEventArgs e) // this works perfectly
{
try { writer.WriteLine("a"); } // attempts to write the ascii 'a' to the arduino which turns on the on-board LED
catch { Debug_Block.Text = "Failed to write"; }
}
private void SendButton_Off_Tap(object sender, System.Windows.Input.GestureEventArgs e) // this works perfectly
{
try { writer.WriteLine("b"); } // attempts to write the ascii 'b' to the arduino which turns off the on-board LED
catch { Debug_Block.Text = "Failed to write"; }
}
private void ReadButtonToggle_Tap(object sender, System.Windows.Input.GestureEventArgs e) // toggles the timer on and off
{
if(Timer.IsEnabled == true)
{
Timer.Stop();
Debug_Block.Text = "Timer Stopped";
}
else
{
Timer.Start();
Debug_Block.Text = "Timer Started";
}
}
void Timer_Tick(object sender, EventArgs e) // THIS IS THE PROBLEM
{
Debug_Block.Text = "Tick";
Debug_Block.Text = reader.ReadLine(); // <-- ALWAYS FREEZES HERE
Timer.Stop(); // This line is temporary for debugging
}
}
}

jsp mysql server connection timeout

hi i am doing an jsp project. and i deploy my project on apache tomcat. i use mysql as databese.
when i deploy project on remote server it is run good. but after some hours it gives me sql error. then i go back my apache server and start projecet again it run and after some hours it gives me same sql error again. i dont know the problem. is that caused from my java connection code or it is about mysql server. can some one tell me why it gives me sql error.?
public class ConnectionManager {
private String className = "com.mysql.jdbc.Driver";
private String userName ="username";
private String password = "password";
private String url = "jdbc:mysql://localhost:3306/database?useUnicode=true&characterEncoding=utf-8";
/**
* #uml.property name="connectionInstance"
* #uml.associationEnd
*/
private static ConnectionManager connectionInstance = null;
public ConnectionManager(){
}
public static synchronized ConnectionManager getInstance() {
if(connectionInstance == null) {
connectionInstance = new ConnectionManager();
}
return connectionInstance;
}
public Connection getConnection(){
Connection conn = null;
try {
Class.forName(className);
conn = DriverManager.getConnection (url, userName, password);
System.out.println("Connection Established");
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
return conn;
}
MySQL has a default connection timeout of 8 hours. So this means that you've kept a SQL connection open for too long. Your code suggests that you're creating only one connection on application's startup and reusing it application wide. This is very bad. This is not threadsafe.
You need to change your code so that you're not declaring and storing the SQL Connection as a static or instance variable anywhere in your code. Instead, it should be declared, created and closed within the shortest possible scope. Preferably within the very same method block as where you're executing the SQL query.
Here's a minor rewrite of your ConnectionManager which does the job properly:
public class ConnectionManager {
private static final String DRIVER = "com.mysql.jdbc.Driver";
private static final String USERNAME ="username";
private static final String PASSWORD = "password";
private static final String URL = "jdbc:mysql://localhost:3306/database?useUnicode=true&characterEncoding=utf-8";
static {
try {
Class.forName(DRIVER);
}
catch (ClassNotFoundException e) {
throw new ExceptionInInitializerError(DRIVER + " missing in classpath!", e);
}
}
public static Connection getConnection() throws SQLException {
return DriverManager.getConnection(URL, USERNAME, PASSWORD);
}
}
Use it as follows:
public class SomeDAO {
public SomeEntity find(Long id) throws SQLException {
Connection connection = null;
// ...
try {
connection = ConnectionManager.getConnection();
// ...
}
finally {
// ...
if (connection != null) try { connection.close(); } catch(SQLException ignore) {}
}
return someEntity;
}
To improve connecting performance, use a connection pool instead of DriverManager.
See also:
Show JDBC ResultSet in HTML in JSP page using MVC and DAO pattern
Are you closing connections properly after using them.