problem in finding the data - java

while i am finding the data the field of TelephoneNo showing the result in float like 54435435.0.even when i inserted this phone no as 54435435 my code is
String findby =cbfind.getSelectedItem().toString();
if(findby.equals("")){
JOptionPane.showMessageDialog(null," SELECT EITHER REGISTRATION NO OR NAME");
return;
}
if(findby.equals("RegNo"))
{
int regno1= Integer.parseInt(cbregn.getSelectedItem().toString());
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
System.out.println("\n Driver loaded");
Connection con=DriverManager.getConnection("jdbc:odbc:wanisamajDB");
Statement stmt=con.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM REGISTRATION1 WHERE RegistrationNo="+regno1);
System.out.println("Hi");
rs.next();
String per = rs.getString("SeniorPerson");
System.out.println("SeniorPerson: " + per );
String reg = rs.getString("RegistrationNo");
System.out.println("RegistrationNo: " + reg);
String nplace = rs.getString("NativePlace");
System.out.println("NativePlace: " + nplace);
String kul = rs.getString("Kul");
System.out.println("Kul: " + kul);
String gtr = rs.getString("Gotra");
System.out.println("Gotra: " + gtr);
String ksami = rs.getString("KulSwami");
System.out.println("KulSwami: " + ksami);
String raddr = rs.getString("ResidensialAddress");
System.out.println("ResidensialAddress: " + raddr);
String code = rs.getString("PinCode");
System.out.println("PinCode: " + code);
String stdcd = rs.getString("STDcode");
System.out.println("STDcode: " + stdcd);
String teleno = rs.getString("TelephoneNo");
System.out.println("TelephoneNo: " + teleno);
String mno = rs.getString("MobileNo");
System.out.println("MobileNo: " + mno);
String email = rs.getString("Email");
System.out.println("Email: " + email);
String web = rs.getString("Website");
System.out.println("Website: " + web);
String educ = rs.getString("Education");
System.out.println("Education: " + educ);
String brch = rs.getString("Branch");
System.out.println("Branch: " + brch);
String bgrp = rs.getString("BloodGroup");
System.out.println("BloodGroup: " + bgrp);
JOptionPane.showMessageDialog(null, "RECORD FOUND");
cbnm.setSelectedItem(per);
tfplace.setText(nplace);
tfkul.setText(kul);
tfgotra.setText(gtr);
tfswami.setText(ksami);
taraddr.setText(raddr);
tfpcd.setText(code);
tfstdcode.setText(stdcd);
tftele.setText(teleno);
tfmno.setText(mno);
tfemail.setText(email);
tfweb.setText(web);
tfedu.setText(educ);
tfbrch.setText(brch);
cbbldgrp.setSelectedItem(bgrp);
}
catch (Exception e)
{
System.out.println("EXCEPTION " + e);
}
}
if(findby.equals("Name"))
{
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
System.out.println("\n Driver loaded");
Connection con=DriverManager.getConnection("jdbc:odbc:wanisamajDB");
Statement stmt=con.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM REGISTRATION1 WHERE SeniorPerson='"+cbnm.getSelectedItem().toString()+"'");
System.out.println("Hi");
rs.next();
String per = rs.getString("SeniorPerson");
System.out.println("SeniorPerson: " + per );
String reg = rs.getString("RegistrationNo");
System.out.println("RegistrationNo: " + reg);
String nplace = rs.getString("NativePlace");
System.out.println("NativePlace: " + nplace);
String kul = rs.getString("Kul");
System.out.println("Kul: " + kul);
String gtr = rs.getString("Gotra");
System.out.println("Gotra: " + gtr);
String ksami = rs.getString("KulSwami");
System.out.println("KulSwami: " + ksami);
String raddr = rs.getString("ResidensialAddress");
System.out.println("ResidensialAddress: " + raddr);
String code = rs.getString("PinCode");
System.out.println("PinCode: " + code);
String stdcd = rs.getString("STDcode");
System.out.println("STDcode: " + stdcd);
String teleno = rs.getString("TelephoneNo");
System.out.println("TelephoneNo: " + teleno);
String mno = rs.getString("MobileNo");
System.out.println("MobileNo: " + mno);
String email = rs.getString("Email");
System.out.println("Email: " + email);
String web = rs.getString("Website");
System.out.println("Website: " + web);
String educ = rs.getString("Education");
System.out.println("Education: " + educ);
String brch = rs.getString("Branch");
System.out.println("Branch: " + brch);
String bgrp = rs.getString("BloodGroup");
System.out.println("BloodGroup: " + bgrp);
JOptionPane.showMessageDialog(null, "RECORD FOUND");
cbregn.setSelectedItem(reg);
tfplace.setText(nplace);
tfkul.setText(kul);
tfgotra.setText(gtr);
tfswami.setText(ksami);
taraddr.setText(raddr);
tfpcd.setText(code);
tfstdcode.setText(stdcd);
tftele.setText(teleno);
tfmno.setText(mno);
tfemail.setText(email);
tfweb.setText(web);
tfedu.setText(educ);
tfbrch.setText(brch);
cbbldgrp.setSelectedItem(bgrp);
}
catch (Exception e)
{
System.out.println("EXCEPTION " + e);
}
}//if

I'm going to wager that it's because that's how it's stored in the DB.
Use varchar rather than whatever it is you're using.

The answer you are seeing is most likely due to:
defining the column type for the telephone number to be "float", "double", "decimal", "numeric" or "real", or
defining the column type as "char", "varchar", etc and populating it from a Java float, double or BigDecimal.
In either case, what you are seeing reflects the data stored in the database.

Related

Java server program is spitting out two U+FFFD characters when launched. Need help figuring out where it does this and why?

I have built a Java server program that is part of an attendance tracker application. It takes in commands from client applications, and performs server functions connected to the database that we have set up. The issue is that once we launch our program, it autmomatically sends the client two U+FFFD characters (the diamond with the question mark symbol) at the beginning of the session, which thus breaks the clients code, and returns errors on their side. I cannot figure out where in the code this is happening, since what is printed to the command line is whats passed to the client. I don't even know where to begin looking. Here is the code for the main file, I'll upload the whole project on Github if needed. I know there's a lot of code there to look through but if anybody can even eyeball the issue right off the bat I'd be so happy. Thank you for the help!
Github: https://github.com/aepries/stacServ.git
package stacserv;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.ObjectOutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.HashMap;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import java.text.Normalizer;
public class StacServ {
/**
* #param args the command line arguments
*/
public static JFrame mainFrame = null;
public static JTextArea chatText = null;
public static StringBuffer toAppend = new StringBuffer("");
public static void initGUI(){
JPanel chatPane = new JPanel(new BorderLayout());
chatText = new JTextArea(20, 20);
chatText.setLineWrap(true);
chatText.setForeground(Color.blue);
chatText.setFont(chatText.getFont().deriveFont(20f));
JScrollPane chatTextPane = new JScrollPane(chatText,
JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
chatPane.add(chatTextPane, BorderLayout.CENTER);
chatPane.setPreferredSize(new Dimension(800, 400));
// Set up the main pane
JPanel mainPane = new JPanel(new BorderLayout());
mainPane.add(chatPane, BorderLayout.CENTER);
// Set up the main frame
mainFrame = new JFrame("Client Messages");
mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainFrame.setContentPane(mainPane);
mainFrame.setSize(mainFrame.getPreferredSize());
mainFrame.setLocation(300, 300);
mainFrame.pack();
mainFrame.setVisible(true);
}
public static void main(String[] args) throws Exception {
initGUI();
ServerSocket m_ServerSocket = new ServerSocket(1025);
int id = 0;
StacServ.chatText.append("Server is now running and listening on port 1025 " + "\n");
while (true) {
Socket clientSocket = m_ServerSocket.accept();
ClientServiceThread cliThread = new ClientServiceThread(clientSocket, id++);
cliThread.start();
}
}
}
class ClientServiceThread extends Thread {
Socket clientSocket;
int clientID = -1;
String userName = null;
boolean running = true;
private MySQLAccess dbconnection;
HashMap<Socket, Integer> connections = new HashMap<Socket, Integer>();
public ArrayList<ClassData> queryResult = new ArrayList<ClassData>();
StringBuilder sb = new StringBuilder();
String commandName = null;
String clientCommand = null;
String restofString = null;
String[] tokens = new String[2];
ClientServiceThread(Socket s, Integer i) {
clientSocket = s;
clientID = i;
connections.put(s, i);
StacServ.chatText.append("Current Connections" + "\n");
for(HashMap.Entry entry: connections.entrySet()){
StacServ.chatText.append(entry.getKey() + ", " + entry.getValue() + "\n");
}
}
#Override
public void run() {
try
{
dbconnection = new MySQLAccess();
dbconnection.connect("138.86.104.164","STACDB","SEClass","BearsRock");
} catch (Exception e) {
//System.out.println(e);
//e.printStackTrace();
}
System.out.println("Accepted Client : ID - " + clientID + " : Address - "
+ clientSocket.getInetAddress().getHostName());
StacServ.chatText.append("Accepted Client : ID - " + clientID + " : Address - "
+ clientSocket.getInetAddress().getHostName()+"\n");
try {
BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
PrintWriter out = new PrintWriter(new OutputStreamWriter(clientSocket.getOutputStream()));
ObjectOutputStream objectOutput = new ObjectOutputStream(clientSocket.getOutputStream());
while (running) {
out.flush();
in.mark(0);
in.reset();
clientCommand = in.readLine();
try{
if(clientCommand == null){
} else {
clientCommand = clientCommand.replace("\"", "");
tokens = clientCommand.split(" ", 2);
commandName = tokens[0];
restofString = tokens[1];
}
} catch(ArrayIndexOutOfBoundsException e) {
//Handle ArrayIndexOutOfBoundsException
}
if (commandName.equalsIgnoreCase("LOGO")) {
System.out.print("Stopping client thread for client : " + clientID);
StacServ.chatText.append("Stopping client thread for client : " + clientID+"\n");
out.println("LOGO" + " logged out."+"\n");
out.flush();
running = false;
}
else if (commandName.equalsIgnoreCase("REGU")){
System.out.println("Client Says :" + clientCommand);
StacServ.chatText.append("Client Says :" + clientCommand+"\n");
String[] keys = restofString.split("\"?( |$)(?=(([^\"]*\"){2})*[^\"]*$)\"?");
String uName = keys[0];
String uPass = keys[1];
String fName = keys[2];
String lName = keys[3];
StacServ.chatText.append("Attemplting to add client: " + fName + " " + lName);
dbconnection.createUser(uName, uPass, fName, lName);
out.println("REGR S");
out.flush();
}
else if (commandName.equalsIgnoreCase("CRCR")){
System.out.println("Client Says :" + clientCommand);
StacServ.chatText.append("Client Says :" + clientCommand+"\n");
String[] keys = restofString.split("\"?( |$)(?=(([^\"]*\"){2})*[^\"]*$)\"?");
String className = keys[0];
String institution = keys[1];
String startDate = keys[2];
String endDate = keys[3];
String ipAddress = keys[4];
String meetDOW = keys[5];
StacServ.chatText.append("Attemplting to add class: " + className);
dbconnection.createClass(className, institution, startDate, endDate, ipAddress, meetDOW);
out.println("CRER S" + className);
out.flush();
}
else if (commandName.equalsIgnoreCase("CSRC")){
System.out.println("Client Says :" + clientCommand);
StacServ.chatText.append("Client Says :" + clientCommand+"\n");
String[] keys = restofString.split("\"?( |$)(?=(([^\"]*\"){2})*[^\"]*$)\"?");
String className = keys[0];
String institution = keys[1];
if(institution == " "){
institution = "%";
}
StacServ.chatText.append("Attemplting to find class: " + className +" " + "\n");
ResultSet rs = dbconnection.searchClasses(className, institution);
//ResultSet rs = dbconnection.searchClasses(className, institution);
while(rs.next()){
queryResult.add(new ClassData(rs.getString("classID"), rs.getString("className"), rs.getString("adminID"), rs.getString("institution"), rs.getString("startDate"), rs.getString("endDate"), rs.getString("PublicIPAddress")));
String ctClassID = rs.getString("classID");
String ctClassName = rs.getString("className");
String ctAdminID = rs.getString("adminID");
String ctinstitution = rs.getString("institution");
String ctstartDate = rs.getString("startDate");
String ctendDate = rs.getString("startDate");
String ctipAddress = rs.getString("endDate");
out.println("CDTR S" + ctClassID + ctClassName + ctAdminID + ctinstitution + ctstartDate + ctendDate + ctipAddress);
StacServ.chatText.append("CDTR S" + " " + ctClassID + " " + ctClassName + " " + ctAdminID + " " + ctinstitution + " " + ctstartDate + " " + ctendDate + " " + ctipAddress + "\n");
}
}
else if (commandName.equalsIgnoreCase("CTDL")){
String[] keys = restofString.split("\"?( |$)(?=(([^\"]*\"){2})*[^\"]*$)\"?");
String classID = keys[0];
int classId = Integer.parseInt(classID);
System.out.println("Client Says :" + clientCommand);
StacServ.chatText.append("Client Says :" + clientCommand+"\n");
StacServ.chatText.append("Attemplting to find class with ID: " + classId + "\n");
ResultSet rs = dbconnection.searchClasses(classId);
while(rs.next()){
queryResult.add(new ClassData(rs.getString("classID"), rs.getString("className"), rs.getString("adminID"), rs.getString("institution"), rs.getString("startDate"), rs.getString("endDate"), rs.getString("PublicIPAddress")));
String ctClassID = rs.getString("classID");
String ctClassName = rs.getString("className");
String ctAdminID = rs.getString("adminID");
String ctinstitution = rs.getString("institution");
String ctstartDate = rs.getString("startDate");
String ctendDate = rs.getString("startDate");
String ctipAddress = rs.getString("endDate");
out.println("CDTR S" + ctClassID + ctClassName + ctAdminID + ctinstitution + ctstartDate + ctendDate + ctipAddress);
StacServ.chatText.append("CDTR " + "S" + ctClassID + ctClassName + ctAdminID + ctinstitution + ctstartDate + ctendDate + ctipAddress + "\n");
}
}
else if (commandName.equalsIgnoreCase("ELST")){
StacServ.chatText.append("ELST TEST " + userName +"\n");
System.out.println("Client Says :" + clientCommand + "\n");
StacServ.chatText.append("Client Says :" + clientCommand+"\n");
int userID = dbconnection.getUserID(userName);
ResultSet userClasses = dbconnection.getStudentsClasses(userID);
String dummy = Integer.toString(userID);
StacServ.chatText.append("userID is: " +dummy +"\n");
StacServ.chatText.append("Attemplting to find classes for user: " + userName + "\n");
sb = new StringBuilder("");
while(userClasses.next()){
String ctClassID = userClasses.getString("classID");
sb.append(ctClassID);
sb.append(" ");
}
out.println("ELSR S" + sb.toString() + "\n");
StacServ.chatText.append("ELSR S" + sb.toString() + "\n");
}
else if (commandName.equalsIgnoreCase("CLST")){
userName = "ejohn";
StacServ.chatText.append("ELST TEST " + userName +"\n");
System.out.println("Client Says :" + clientCommand + "\n");
StacServ.chatText.append("Client Says :" + clientCommand+"\n");
int userID = dbconnection.getAdminsID(userName);
ResultSet userClasses = dbconnection.getAdminClasses(userID);
String dummy = Integer.toString(userID);
StacServ.chatText.append("userID is: " +dummy +"\n");
StacServ.chatText.append("Attemplting to find classes for user: " + userName + "\n");
userName = "CCDawg";
sb = new StringBuilder("");
while(userClasses.next()){
String ctClassID = userClasses.getString("classID");
sb.append(ctClassID);
sb.append(" ");
}
out.println("ELSR S" + sb.toString() + "\n");
StacServ.chatText.append("ELSR " + "S " + sb.toString() + "\n");
}
else if(commandName.equalsIgnoreCase("ENRL")){
System.out.println("Client Says :" + clientCommand);
StacServ.chatText.append("Client Says :" + clientCommand+"\n");
userName = "CCDawg";
String flag = "0";
String[] keys = restofString.split("\"?( |$)(?=(([^\"]*\"){2})*[^\"]*$)\"?");
String classID = keys[0];
String deviceID = keys[1];
int classIDs = Integer.parseInt(classID);
dbconnection.addDevice(userName, classIDs, deviceID, flag);
}
else if(commandName.equalsIgnoreCase("CDRP")){
userName = "PillCosby";
String[] keys = restofString.split("\"?( |$)(?=(([^\"]*\"){2})*[^\"]*$)\"?");
String classID = keys[0];
int classIDs = Integer.parseInt(classID);
dbconnection.unenrollStudent(classIDs, userName);
}
else if (commandName.equalsIgnoreCase("REGA")){
System.out.println("Client Says :" + clientCommand);
StacServ.chatText.append("Client Says :" + clientCommand+"\n");
String[] keys = restofString.split("\"?( |$)(?=(([^\"]*\"){2})*[^\"]*$)\"?");
String uName = keys[0];
String uPass = keys[1];
String fName = keys[2];
String lName = keys[3];
StacServ.chatText.append("Attempting to add Admin: " + fName + " " + lName);
dbconnection.createAdmin(uName, uPass, fName, lName);
out.println("REGA " + "S"+"\n");
out.flush();
}
else if (commandName.equalsIgnoreCase("LOGA")){
ResultSet rs = null;
System.out.println("Client Says :" + clientCommand+"\n");
StacServ.chatText.append("Client Says :" + clientCommand+"\n");
String[] keys = restofString.split("\"?( |$)(?=(([^\"]*\"){2})*[^\"]*$)\"?");
String uName = keys[0];
String uPass = keys[1];
StacServ.chatText.append("Attempting to Login Admin: " + uName+"\n");
rs = dbconnection.checkAdmin(uName);
if(rs != null){
while(rs.next()){
String check = rs.getString(1);
if(uName.equals(check)){
check = rs.getString(2);
if(uPass.equals(check)){
StacServ.chatText.append("Admin: " + uName + " logged in."+"\n");
out.flush();
out.println("LOGR S");
userName = uName;
out.flush();
}
else{
StacServ.chatText.append("Admin: " + uName + "Incorrect username or password"+"\n");
out.flush();
out.println("LOGR " + "F"+"\n");
out.flush();
}
}
}
}
else{
StacServ.chatText.append("Admin: " + uName + "is not registered in the system");
out.println("LOGA " + "F"+"\n");
out.flush();
}
}
else if (commandName.equalsIgnoreCase("LOGU")){
ResultSet rs = null;
System.out.println("Client Says :" + clientCommand);
StacServ.chatText.append("Client Says :" + clientCommand+"\n");
StacServ.chatText.append(restofString +"\n");
//restofString = restofString.replaceAll("[\u0000-\u001f]", "");
String[] keys = restofString.split("\"?( |$)(?=(([^\"]*\"){2})*[^\"]*$)\"?");
String uName = keys[0];
String uPass = keys[1];
uName = uName.replace("\"", "");
uPass = uPass.replace("\"", "");
StacServ.chatText.append("Attempting to log in: " + uName+"\n");
rs = dbconnection.checkUser(uName);
if(rs != null){
while(rs.next()){
String check = rs.getString(1);
if(uName.equals(check)){
check = rs.getString(2);
if(uPass.equals(check)){
StacServ.chatText.append("User: " + uName + " logged in."+"\n");
out.println("LOGR S");
userName = uName;
out.flush();
}
else{
StacServ.chatText.append("User: " + uName + "\n" + "Incorrect password" +"\n");
out.println("LOGR F" + "\n");
out.flush();
}
}
}
}
else{
StacServ.chatText.append("Admin: " + uName + "is not registered in the system");
out.println("LOGR F");
out.flush();
}
}
else {
//out.println(clientCommand);
out.flush();
}
}
} catch (Exception e) {
//e.printStackTrace();
}
}
}
Are you sure you want to use an ObjectOutputStream?
It will output a serialization header to the underlying OutputStream. If you want to avoid that but still have methods for raw data output (which you might not need if you have a line oriented protcol) then a DataOutputStream offers the same methods without the serialisation header.
For a line based protocol StreamWriter is the better alternative.
You can't mix a PrintWriter and an ObjectOutputStream on the same socket, and an ObjectOutputStream sends a stream header when constructed. It starts with 0xAC though, not 0xFFFD.

JDBC incorrect syntax at or near "." executeQuery

This is of course parts of a larger code. It will compile with no problem, but when I call this method I get the error
"syntax error near or at "."" at the position of stmt.executeQuery(SQL).
I would really appreciate the help!
private void Component() {
try {
Statement stmt = con.createStatement();
String SQL = "SELECT component.*, stock.amount_of_component, component.price component.component_type "
+ "FROM component JOIN stock "
+ "ON component.id = stock.component_id "
+ "ORDER BY component.component_type";
ResultSet rs = stmt.executeQuery(SQL);
rs.next();
int id = rs.getInt("ID");
int amount_of_component = rs.getInt("Amount");
String name = rs.getString("Name");
double price = rs.getDouble("Price");
String component_type = rs.getString("Type");
System.out.println(" " + id + amount_of_component + " " + name + " " + price + " " + component_type);
} catch (SQLException err)
{
System.out.println(err.getMessage());
}
}
Typo, missing a comma in the query between component.price and component.component_type :
SELECT component.*, stock.amount_of_component, component.price, component.component_type
FROM component JOIN stock
ON component.id = stock.component_id
ORDER BY component.component_type
Edit: To read the whole result set, put this cycle instead of rs.next()
while(result.next()) {
int id = rs.getInt("ID");
int amount_of_component = rs.getInt("Amount");
String name = rs.getString("Name");
double price = rs.getDouble("Price");
String component_type = rs.getString("Type");
System.out.println(" " + id + amount_of_component + " " + name + " " + price + " " + component_type);
}
Edit2: To print the header, you have to do it manually by putting a System.out.println(" id amount_of_component name price component_type "); before the while.
You missed a comma between 'component.price' and 'component.component_type'

Sql query that outputs to ONE Joptionpane

String sql = "SELECT TOP 10 id, Trailer, Block, Location, Day, SetTime, Comment FROM TrailerLocation"
+ " ORDER BY id DESC";
rs = st.executeQuery(sql);
while(rs.next()){
//Retrieve by column name
int id = rs.getInt("id");
String trailer = rs.getString("Trailer");
String block = rs.getString("Block");
String location = rs.getString("Location");
String date = rs.getString("Day");
String comment = rs.getString("Comment");
//Display values
JOptionPane.showMessageDialog(null,
"ID: " + id
+ ", Trailer: " + trailer
+ ", Block: " + block
+ ", Location: " + location
+ ", Date & Time: " + date
+ ", Comment: " + comment);
}
I want the Joptionpane to only display once with all the data not ten times.
You could move the JOptionPane.showMessageDialog(null, ... ) after the while loop.
And, in the while loop, add the informations you want in one unique string which you will display in you JOptionPane.
rs = st.executeQuery(sql);
StringBuilder str = new StringBuilder();
while(rs.next()){
//Retrieve by column name
str.append("ID: " + rs.getInt("id"));
str.append(", Trailer: " + rs.getString("Trailer"));
str.append(", Block: " + rs.getString("Block"));
str.append(", Location: " + rs.getString("Location"));
str.append(", Date: " + rs.getString("Day"));
str.append(", Comment: " + rs.getString("Comment"));
//new line
str.append("\n");
}
JOptionPane.showMessageDialog(null,str.toString());

ResultSet with variable

Ok so basically I have this code:
resultSet = statement.executeQuery("select * from FEEDBACK.COMMENTS");
writeResultSet(resultSet);
private void writeResultSet(ResultSet resultSet) throws SQLException {
System.out.println("jestem w writeresultset");
// resultSet is initialised before the first data set
while (resultSet.next()) {
// it is possible to get the columns via name
// also possible to get the columns via the column number
// which starts at 1
// e.g., resultSet.getSTring(2);
String id = resultSet.getString("id");
String user = resultSet.getString("IMIE");
String website = resultSet.getString("NAZWISKO");
String summary = resultSet.getString("ADRES");
String date = resultSet.getString("EMAIL");
String comment = resultSet.getString("TELEFON");
String opisso = resultSet.getString("OPIS");
JTextField myOutput = new JTextField(1600);
myOutput.setText("id w bazie danych to " + id + " imie to " + user
+ " nazwisko to " + website + " adres to " + summary + " email to "
+ date + " teelefon to " + comment + " opis to " + opisso);
add(myOutput);
}
}
What I want to achieve is this:
resultSet = statement.executeQuery("select * from FEEDBACK.COMMENTS
where NAZWISKO LIKE " variable );
writeResultSet(resultSet);
I want to search by variable which is already defined, however I'm stuck and have no idea how to do it like that.
Use PreparedStatement:
String nazwisko = ...
String query = "select * from FEEDBACK.COMMENTS where NAZWISKO LIKE ?";
PreparedStatement pstmt = con.prepareStatement(query);
pstmt.setString(1, nazwisko);
ResultSet rs = pstmt.execute();
while (resultSet.next()) {
//...
}
In case you need to use a wildcard for your LIKE, choose one of these:
nazwisko = nazwisko + "%";
nazwisko = "%" + nazwisko;
nazwisko = "%" + nazwisko + "%";
up , there are alot weird errors with your code:
like cannot find symbol variable con or incompatible type boolean cannot be converted to resultset.
I have tried this: but there is an error when executing
preparedStatement = connect
.prepareStatement("select * from FEEDBACK.COMMENTS where NAZWISKO= ? ; ");
preparedStatement.setString(1, surname3);
while (resultSet.next()) {
String id = resultSet.getString("i
d");
String user = resultSet.getString("IMIE");
String website = resultSet.getString("NAZWISKO");
String summary = resultSet.getString("ADRES");
String date = resultSet.getString("EMAIL");
String comment = resultSet.getString("TELEFON");
String opisso = resultSet.getString("OPIS");
JTextField myOutput = new JTextField(1600);
myOutput.setText("id w bazie danych to " + id + " imie to " + user + " nazwisko to " + website + " adres to " + summary + " email to " + date + " teelefon to " + comment + " opis to " + opisso);
add(myOutput);
}
error:
the query went fine but , the error appears here "while (resultSet.next())"
SEVERE: null
java.lang.NullPointerException
at jdbcexample.Main.readDataBase(Main.java:416)
at jdbcexample.Main$7.mousePressed(Main.java:346)

I have a basic Update Where statement that is sytaxticly correct but does not update the table

This is the code:
#Override public void update(){
Statement stmt = null;
String company = "";
try {
Connect conn = new Connect();
stmt = conn.makeStatement();
// This creates the SQL statement to update an existing student.
System.out.println("Update employee"
+ " Set employeeID = employeeID,"
+ " firstName = firstName,"
+ " lastName = lastName,"
+ " paRating = paRating,"
+ " status = status,"
+ " manager = managerr,"
+ " level = level,"
+ " company = company"
+ " WHERE employeeID = " + get EmployeeID()
+ "Limit 1");
stmt.execute("Update employee"
+ " Set employeeID = employeeID,"
+ " firstName = firstName,"
+ " lastName = lastName,"
+ " paRating = paRating,"
+ " status = status,"
+ " manager = managerr,"
+ " level = level,"
+ " company = company"
+ " WHERE employeeID = " + get EmployeeID()
+ "Limit 1");
stmt.close();
conn.close();
} catch (SQLException e) {
e.printStackTrace();
System.err.println("Unable to update employee in the database.");
} finally {
}
System.out.println("Employee successfully updated to the database.");
}
I am assuming I have missed something simple & obvious that i just can't see.
This query doesn't update anything - it just sets a whole lot of columns to their existing values. If you want to update them to something else, you'd better pass those "something else" values in somehow.
Two things I note, you probably want a space between getEmployeeID() and Limit 1; Also, assuming you're not running with autoCommit enabled, you need to call Connection.commit(). Finally, you should close your connection and statement objects in the finally block.

Categories