my javafx project doesn't read data from the database - sql

So i created a database table in intellij and i made a javafx project and it's connected to my server(localhost)
now i'm getting errors here
String query = "SELECT * FROM IntellijDB.dbo.Employee WHERE username = ? and passcode = ?";
it says I'm unable to access the table
this is the method
public boolean isLogin(String user,String pass) throws SQLException
{
PreparedStatement preparedStatement = null ;
ResultSet resultSet = null;
String query = "SELECT * FROM IntellijDB.dbo.Employee WHERE username = ? and passcode = ?";
try
{
preparedStatement = connection.prepareStatement(query);
preparedStatement.setString(1,user);
preparedStatement.setString(2,pass);
resultSet = preparedStatement.executeQuery();
if (resultSet.next())
{
return true;
}
else
{
return false;
}
}
catch (Exception e)
{
return false;
//TODO: handle exception
}
finally {
preparedStatement.close();
resultSet.close();
}
}
and the other error here
if (loginModel.isLogin(userAction.getText(), passAction.getText()))
and this line too
resultSet.close();
and I guess they are related and i don't know how to fix this
this is the other code
#FXML
public void Login(ActionEvent event) {
try {
if (loginModel.isLogin(userAction.getText(), passAction.getText())) {
isConnected.setText("Username & password is correct");
}
else
{
isConnected.setText("Check your username or password");
}
} catch (SQLException e)
{
isConnected.setText("Check your username or password");
//TODO Auto-generated catch block
e.printStackTrace();
}
}

Related

Reading a table from database

I having a problem to run below Java code. I couldn't find the DB.java class.
ResultSet rs = DB.getConnection().createStatement().executeQuery("select * from products");
while(rs.next()){
System.out.print(rs.getString("pid"));
System.out.print(rs.getString("name"));
System.out.print(rs.getString("price"));
System.out.print(rs.getString("ava_qty"));
}
I'm using Glassfish server. Can someone help me to write the DB.java class?
The getConnection() method is part of the DriverManager class. Initialize your drivermanager properly, as described in this post:
https://www.tutorialspoint.com/javaexamples/jdbc_dbconnection.htm
Example code for future reference:
import java.sql.*;
public class jdbcConn {
public static void main(String[] args) {
try {
Class.forName("org.apache.derby.jdbc.ClientDriver");
} catch(ClassNotFoundException e) {
System.out.println("Class not found "+ e);
}
System.out.println("JDBC Class found");
int no_of_rows = 0;
try {
Connection con = DriverManager.getConnection (
"jdbc:derby://localhost:1527/testDb","username", "password");
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery ("SELECT * FROM employee");
while (rs.next()) {
no_of_rows++;
}
System.out.println("There are "+ no_of_rows + " record in the table");
} catch(SQLException e){
System.out.println("SQL exception occured" + e);
}
}
}

Why is Entity Framework inserting duplicating records into table

For some reason .Net Entity Framework is inserting multiple duplicate records into a table called groups in my database. It seems to be occurring when a user logs in and access group index page.
Here are code snippets of my Index page controller code, as well as the DataContext get method and update method for Groups.
I'm not seeing whats wrong here as I'm only building a model and returning it to Index view. Anyone have any suggestions? I'm using MVC 4, Entity Framework 6.
Screenshot of records: It goes on for 50 rows like this.
Index View Controller
[Authorize(Roles = "Standard, Administrator")]
public ActionResult Index()
{
int _userId = WebSecurity.CurrentUserId;
var model = new GroupIndexModel();
if (Roles.GetRolesForUser().Contains("Administrator"))
{
ViewBag.Role = "Administrator";
var modelList = model.BuildIndexModel(_ctx.Groups.GetAllGroups());
modelList.CampaignTemplates = _ctx.Templates.GetAllCampaignTemplateList();
modelList.ProcedureTemplates = _ctx.Templates.GetAllProcedureTemplateList();
return View(modelList);
}
else
{
ViewBag.Role = "Standard";
var userGroups = _ctx.ManyToManyRelationShips.GetUserGroups(_userId);
var modelList = model.BuildIndexModel(_ctx.ManyToManyRelationShips.GetGroupsEntitiesForUser(userGroups));
foreach( var group in modelList.GroupObjects)
{
modelList.CampaignTemplates = _ctx.Templates.GetAllCampaignTemplateList().FindAll(p => p.GroupID == group.GroupId);
}
var tempProcTemplateList = _ctx.Templates.GetAllProcedureTemplateList();
foreach (var cTemplate in modelList.CampaignTemplates)
{
modelList.ProcedureTemplates.AddRange(tempProcTemplateList.FindAll(p => p.CampaignTemplateID == cTemplate.CampaignTemplateId));
}
return View(modelList);
}
}
Groups Manager (Get, GetAll, Add, Update Functions)
public Group Get(int groupId)
{
try
{
var group = new Group();
var temp = _ctx.Groups.First(p => p.GroupId == groupId);
if (temp != null)
{
group.GroupId = temp.GroupId;
group.CompanyName = temp.CompanyName;
group.Email = temp.Email;
group.PhoneNumber = temp.PhoneNumber;
group.CreatedDate = temp.CreatedDate;
group.LastModifiedDate = temp.LastModifiedDate;
}
return group;
}
catch (Exception ex)
{
logger.Error("An Error occured getting a group", ex);
// Console.WriteLine("An Error occured getting a group" + System.Environment.NewLine + ex);
return null;
}
}
public List<Group> GetAllGroups()
{
try
{
var groupList = _ctx.Groups.OrderBy(p => p.CompanyName).ToList<Group>();
return groupList;
}
catch (Exception ex)
{
logger.Error("An Error occured getting groups", ex);
//Console.WriteLine("An Error occured getting groups" + System.Environment.NewLine + ex);
return null;
}
}
public int Add(Group eGroup)
{
int newGroupId;
try
{
_ctx.Groups.Add(eGroup);
_ctx.SaveChanges();
newGroupId = eGroup.GroupId;
return newGroupId;
}
catch (Exception ex)
{
logger.Error("An Error occured adding group", ex);
//Console.WriteLine("An Error occured adding group" + System.Environment.NewLine + ex);
return -1;
}
}
public void UpdateGroup(Group eGroup)
{
try
{
var updev = _ctx.Groups.First(p => p.GroupId == eGroup.GroupId);
if (updev.CompanyName != eGroup.CompanyName)
updev.CompanyName = eGroup.CompanyName;
if (updev.Email != eGroup.Email)
updev.Email = eGroup.Email;
if (updev.PhoneNumber != eGroup.PhoneNumber)
updev.PhoneNumber = eGroup.PhoneNumber;
updev.LastModifiedDate = DateTime.Now;
_ctx.SaveChanges();
}
catch (Exception ex)
{
logger.Error("An Error occured updating group", ex);
// Console.WriteLine("An Error occured updating group" + System.Environment.NewLine + ex);
return;
}
}

Extract result of sql request in a rest webservice

I am using this code to create a login webservice to database
public class classeConnection {
#GET
#Path (value="log/{a}/{b}")
#Produces(MediaType.APPLICATION_JSON)
public String execMAJ(#PathParam("a")String name,#PathParam("b")String lastname )throws SQLException {
String req;
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e ){};
Connection cn= DriverManager.getConnection("jdbc:mysql://localhost:3306/codezone4", "root","");
Statement st=cn.createStatement();
req="select id from utilisateur where nom = '+name+' and prenom = '+lastname+' ";
st.close();
cn.close();
System.out.println("success");
return "login";
}
}
My code is working but I don't know how to extract the result of the sql request ( here id )
Are there any suggestions to this issue? Please help!
public class classeConnection {
#GET
#Path (value="log/{a}/{b}")
#Produces(MediaType.APPLICATION_JSON)
public String execMAJ(#PathParam("a")String name,#PathParam("b")String lastname )throws SQLException {
String req;
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e ){
e.printStackTrace();
}
try {
Connection cn= DriverManager.getConnection("jdbc:mysql://localhost:3306/codezone4", "root","");
Statement st=cn.createStatement();
req="select id from utilisateur where nom = "+name+" and prenom = "+lastname+" LIMIT 1";
ResultSet res = st.executeQuery(req);
if(res.first()) {
String id = res.getString("id");
System.out.println("id = "+id);
} else {
System.out.println("not found foo!");
}
}
catch (SQLException s){
s.printStackTrace();
}
catch (Exception e){
e.printStackTrace();
}
finally {
st.close();
cn.close();
}
return "login";
}
}

Java + Sql database data rollback is not working

In my application, I am writing data to a database.
This is the code for database writing.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class DatabaseRollback {
private static Connection getDBConnection() {
Connection dbConnection = null;
try {
Class.forName("org.postgresql.Driver");
} catch (ClassNotFoundException e) {
System.out.println("Where is your PostgreSQL JDBC Driver? " + "Include in your library path!");
System.out.println(e.getMessage());
e.printStackTrace();
}
System.out.println("PostgreSQL JDBC Driver Registered!");
try {
dbConnection = DriverManager.getConnection("jdbc:postgresql://127.0.0.1:5432/MyDB","root","123");
if (dbConnection != null) {
System.out.println("You made it, take control your database now!");
} else {
System.out.println("Failed to make connection!");
}
return dbConnection;
} catch (SQLException e) {
System.out.println("Connection Failed! Check output console");
System.out.println(e.getMessage());
e.printStackTrace();
}
return dbConnection;
}
public static void main(String args[]) throws SQLException {
Connection dbConnection = null;
PreparedStatement pstmt = null;
String query = "insert into orders(orderid, execid, exectype, lastprice, lastqty, ordstatus) values(?, ?, ?, ?, ?, ?)";
try {
dbConnection = getDBConnection();
dbConnection.setAutoCommit(false);
pstmt = dbConnection.prepareStatement(query); // create a statement
pstmt.setString(1, "OrderID");
pstmt.setString(2, "Test02");
pstmt.setString(3, "exectype");
pstmt.setDouble(4, 100.00);
pstmt.setInt(5, 100);
pstmt.setString(6,"ordstatus");
pstmt.executeUpdate();
dbConnection.commit();
query.concat("error");
dbConnection.prepareStatement(query);
pstmt.setString(1, "eeeeeeeeeeeeeeeeeeeeeeee");
pstmt.executeUpdate(); // here error comes.........
} catch (Exception e) {
// e.printStackTrace();
dbConnection.rollback();
}
finally {
if (pstmt != null) {
pstmt.close();
}
if (dbConnection != null && !dbConnection.isClosed()) {
dbConnection.close();
}
}
}}
After debug point reach to the dbConnection.commit(); I have checked database and one record was inserted. But then it goes through dbConnection.rollback(); section. but it doesn't rollback inserted record. How can I implement rollback machanism?
dbConnection.commit();
should be placed at the end of your transaction.
pstmt.setString(1, "eeeeeeeeeeeeeeeeeeeeeeee");
pstmt.executeUpdate(); // here error comes.........
dbConnection.commit();
} catch (Exception e) {

java mail keeping Transport object connected

How do i keep the java mail transport object alive or connected.
I have written this in my code in a simple class file inside a web application : -
#Resource(name = "myMailServer")
private Session mailSession;
Transport transport ;
public boolean sendMail(String recipient, String subject, String text) {
boolean exe = false;
Properties p = new Properties();
String username = "someone#gmail.com";
String password = "password";
InitialContext c = null;
try
{
c = new InitialContext();
mailSession = (javax.mail.Session) c.lookup("java:comp/env/myMailServer");
}
catch(NamingException ne)
{
ne.printStackTrace();
}
try
{
Message msg = new MimeMessage(mailSession);
msg.setRecipients(Message.RecipientType.TO,InternetAddress.parse(recipient, false));
msg.setSubject(subject);
msg.setText(text);
msg.setHeader("MIME-Version" , "1.0" );
msg.setHeader("Content-Type" , "text/html" );
msg.setHeader("X-Mailer", "Recommend-It Mailer V2.03c02");
msg.saveChanges();
//Transport.send(msg);
if(transport == null) {
transport = mailSession.getTransport("smtps");
System.out.println("" + transport.isConnected());
if(!transport.isConnected()) {
transport.connect(username, password);
}
}
transport.sendMessage(msg, msg.getAllRecipients());
exe = true;
}
catch (AddressException e)
{
e.printStackTrace();
exe = false;
}
catch (MessagingException e)
{
e.printStackTrace();
exe = false;
}
finally {
/*try {
if(transport != null)
transport.close();
}
catch(MessagingException me) {
me.printStackTrace();
}
catch(Exception e) {
e.printStackTrace();
}*/
}
return exe;
}
the full code here
Now everytime i run this code it takes some time to connect with the mail server
and the line
System.out.println("" + transport.isConnected());
prints a false
How do i retain the object transport as it does gets null and into the block
if(transport == null) {
or the transport object remains connected...
Thanks
Pradyut
the code should be....
with a static initialization of transport object
without any problems but can be good with a function
static Transport getTransport() method
#Resource(name = "myMailServer")
private Session mailSession;
static Transport transport ;
public boolean sendMail(String recipient, String subject, String text) {
boolean exe = false;
Properties p = new Properties();
String username = "someone#gmail.com";
String password = "password";
InitialContext c = null;
try
{
c = new InitialContext();
mailSession = (javax.mail.Session) c.lookup("java:comp/env/myMailServer");
}
catch(NamingException ne)
{
ne.printStackTrace();
}
try
{
Message msg = new MimeMessage(mailSession);
msg.setRecipients(Message.RecipientType.TO,InternetAddress.parse(recipient, false));
msg.setSubject(subject);
msg.setText(text);
msg.setHeader("MIME-Version" , "1.0" );
msg.setHeader("Content-Type" , "text/html" );
msg.setHeader("X-Mailer", "Recommend-It Mailer V2.03c02");
msg.saveChanges();
//Transport.send(msg);
if(transport == null) {
transport = mailSession.getTransport("smtps");
}
if(!transport.isConnected()) {
transport.connect(username, password);
}
transport.sendMessage(msg, msg.getAllRecipients());
exe = true;
}
catch (AddressException e)
{
e.printStackTrace();
exe = false;
}
catch (MessagingException e)
{
e.printStackTrace();
exe = false;
}
finally {
/*try {
if(transport != null)
transport.close();
}
catch(MessagingException me) {
me.printStackTrace();
}
catch(Exception e) {
e.printStackTrace();
}*/
}
return exe;
}
Thanks
Regards
Pradyut