Exception in thread "main" com.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException: Could not create connection to database server. Attempted reconnect 3 times. Giving up.
public class MyClass {
public static void main(String[] args) throws Exception {
String url= "jdbc:mysql://localhost:3306/first/?useUnicode=yes&autoReconnect=true&useSSL=false";
String uname="root";
String pass="****";
Class.forName("com.mysql.jdbc.Driver");
Connection con= DriverManager.getConnection(url,uname,pass);
Statement st= con.createStatement();
ResultSet rs=st.executeQuery("select name from sample_t where rollno=1");
rs.next();
String name1=rs.getString("name");
System.out.println(name1);
st.close();
con.close();
}
}
Please Check whether your MySQL Server is running or not.
Check your MySQL connection is up or not and try changing the url as below:
String url= "jdbc:mysql://localhost/first/?useUnicode=yes&autoReconnect=true&useSSL=false";
You can try this approach
try
{
Class.forName("com.mysql.jdbc.Driver");
String url="jdbc:mysql://localhost:3306/first";
String user="root";
String pass="****";
con=DriverManager.getConnection(url,user,pass);
String query="select name from sample_t where rollno=?";
pstmt=con.prepareStatement(query);
System.out.println("Enter user id : ");
pstmt.setInt(1, sc.nextInt());
rs=pstmt.executeQuery();
//Process the result
if(rs.next())
{
System.out.println("Roll No. : " +rs.getInt(1));
}
//closing connections
sc.close();
pstmt.close();
rs.close();
con.close();
}
catch (Exception e)
{`
e.printStackTrace();
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.