After successful connection with sql server (using wamp), ive added a simple table with 1 column and one value, so im trying to take that value and update the jlist. It shows no error and it doesnt work,forgive me if im done someting stupid. (Also im writing this inside a jcombobox event handler)
private void jComboBox1ActionPerformed(java.awt.event.ActionEvent evt) {
String a = null;
String que="SELECT * FROM game";
Connection dn=null;
Statement st=null;
ResultSet sm=null;
String db="jdbc:mysql://localhost:3306/project";
try{
dn=DriverManager.getConnection(db, "user", "");
st=dn.prepareStatement(que);
sm=st.executeQuery(que);
while(sm.next())
{
a=sm.getString(1);
}
DefaultListModel n=new DefaultListModel();
n.addElement(a);
jList1.setModel(n);
}
catch(SQLException e)
{
}
}
Related
My SELECT_QUERY_RETURNS_LIST returns 5 results, But following while loop prints only 4.
jdbcTemplate.query(SELECT_QUERY_RETURNS_LIST, new RowCallbackHandler() {
public void processRow(ResultSet resultSet) throws SQLException {
int count = 1;
while (resultSet.next()) {
String payload = resultSet.getString(1);
LOGGER.info("My result {}...",count++);
}
}
});
Logically It is correct as spring jdbc RowCallbackHandler tells
rs - the ResultSet to process (pre-initialized for the current row)
In firstline Itself we told resultSet.next(), So It starts from second record which results in printing 4 records. And following code works as my expcectation
jdbcTemplate.query(SELECT_QUERY_RETURNS_LIST, new RowCallbackHandler() {
public void processRow(ResultSet resultSet) throws SQLException {
int count = 1;
String payload = resultSet.getString(1);
LOGGER.info("My result {}...",count++);
while (resultSet.next()) {
payload = resultSet.getString(1);
LOGGER.info("My result {}...",count++);
}
}
});
So please tell solution to minimize code before while loop.
Issue has been resolved by using do while instead of while loop
jdbcTemplate.query(SELECT_QUERY_RETURNS_LIST, new RowCallbackHandler() {
public void processRow(ResultSet resultSet) throws SQLException {
int count = 1;
do {
payload = resultSet.getString(1);
LOGGER.info("My result {}...",count++);
} while (resultSet.next());
}
});
You don't need to write a loop with RowCallbackHandler interface. It is used inside JdbcTemplate.RowCallbackHandlerResultSetExtractor and there is already a while loop over ResultSet entries.
The only problem is that there is no index in RowCallbackHandler.processRow signature, so you have to rely on an external counter, I suppose.
My aim is to test if the user and password inserted, existed in Table1.
However, if I typed (pink,floyd) which exists in the database count still null and it appears the message "user doesn't exist".
b.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
try {
String user=f_user.getText().trim();
String pass=f_pass.getText().trim();
String sql="select user, pass from \"Table1\" where user='"+user+"' and pass='"+pass+"'";
rs=stat.executeQuery(sql);
int count=0;
while(rs.next()){
count++;
}
if (count==0) JOptionPane.showMessageDialog(null, "user doesn't exist");
else JOptionPane.showMessageDialog(null, "acces permitted");
} catch ( Exception ex) {
Logger.getLogger(Login.class.getName()).log(Level.SEVERE, null, ex);
}
}
Here's my database :
First problem you had - cos you updated was that your sql was invalid. you're missing FROM.
You had created table1 but sql is from table2.
It turns that the stocked user and pass parameters in Table1 hasn't the same length of input parameters . So , we need to change :
String sql="select user, pass from \"Table1\" where user='"+user+"' and pass='"+pass+"'";
to
String sql="select * from \"Table1\" where trim(\"user\")= '"+user+"' and trim(\"pass\")= '"+pass+"'";
I have a script which is loading some data about venues:
venues = LOAD 'venues_extended_2.csv' USING org.apache.pig.piggybank.storage.CSVLoader() AS (Name:chararray, Type:chararray, Latitude:double, Longitude:double, City:chararray, Country:chararray);
Then I want to create UDF which has a constructor that is accepting venues type.
So I tried to define this UDF like that:
DEFINE GenerateVenues org.gla.anton.udf.main.GenerateVenues(venues);
And here is the actual UDF:
public class GenerateVenues extends EvalFunc<Tuple> {
TupleFactory mTupleFactory = TupleFactory.getInstance();
BagFactory mBagFactory = BagFactory.getInstance();
private static final String ALLCHARS = "(.*)";
private ArrayList<String> venues;
private String regex;
public GenerateVenues(DataBag venuesBag) {
Iterator<Tuple> it = venuesBag.iterator();
venues = new ArrayList<String>((int) (venuesBag.size() + 1)); // possible fails!!!
String current = "";
regex = "";
while (it.hasNext()){
Tuple t = it.next();
try {
current = "(" + ALLCHARS + t.get(0) + ALLCHARS + ")";
venues.add((String) t.get(0));
} catch (ExecException e) {
throw new IllegalArgumentException("VenuesRegex: requires tuple with at least one value");
}
regex += current + (it.hasNext() ? "|" : "");
}
}
#Override
public Tuple exec(Tuple tuple) throws IOException {
// expect one string
if (tuple == null || tuple.size() != 2) {
throw new IllegalArgumentException(
"BagTupleExampleUDF: requires two input parameters.");
}
try {
String tweet = (String) tuple.get(0);
for (String venue: venues)
{
if (tweet.matches(ALLCHARS + venue + ALLCHARS))
{
Tuple output = mTupleFactory.newTuple(Collections.singletonList(venue));
return output;
}
}
return null;
} catch (Exception e) {
throw new IOException(
"BagTupleExampleUDF: caught exception processing input.", e);
}
}
}
When executed the script is firing error at the DEFINE part just before (venues);:
2013-12-19 04:28:06,072 [main] ERROR org.apache.pig.tools.grunt.Grunt - ERROR 1200: <file script.pig, line 6, column 60> mismatched input 'venues' expecting RIGHT_PAREN
Obviously I'm doing something wrong, can you help me out figuring out what's wrong.
Is it the UDF that cannot accept the venues relation as a parameter. Or the relation is not represented by DataBag like this public GenerateVenues(DataBag venuesBag)?
Thanks!
PS I'm using Pig version 0.11.1.1.3.0.0-107.
As #WinnieNicklaus already said, you can only pass strings to UDF constructors.
Having said that, the solution to your problem is using distributed cache, you need to override public List<String> getCacheFiles() to return a list of filenames that will be made available via distributed cache. With that, you can read the file as a local file and build your table.
The downside is that Pig has no initialization function, so you have to implement something like
private void init() {
if (!this.initialized) {
// read table
}
}
and then call that as the first thing from exec.
You can't use a relation as a parameter in a UDF constructor. Only strings can be passed as arguments, and if they are really of another type, you will have to parse them out in the constructor.
I'm trying to get results from a rather trivial query, and write out those results on a jsp page. Running Glassfish 3.1, using Netbeans. When I run the project, I get an empty list returned from the routine.
When I right click the table in Services and hit View Data, I can see the table is populated, and when I copy and past the query into the SQL Command window and run it, it gives the expected list of length 2.
There are a few similar questions (like this one), none of which seemed to be of much help. I am new at this, so I may not have understood a solution to one of the other questions.
There are a lot of factors at play here, and I'm not really sure what to include. I have included the routine doing the query, the JSP Code calling that routine, the entity class I'm using, and the output of the server log that I get when the project is run. If more information is needed, let me know and I'll put it up.
I really appreciate any help.
Griff
Routine doing the query:
public static LinkedList<String> getCategories(EntityManager entityManager) {
try {
Query query = entityManager.createQuery(
"SELECT DISTINCT i.category from ItemEntity i");
List resultList = query.getResultList();
if (!resultList.isEmpty()) {
return new LinkedList<String>(resultList);
}
} catch(Exception e) {
System.out.println(e);
} finally {
return new LinkedList<String>();
}
}
The JSP Code calling the routine:
<body>
<h1>Store</h1>
<h2>Categories</h2>
<%
Context environmentContext
= (Context) new InitialContext().lookup("java:comp/env");
EntityManager entityManager
= (EntityManager) environmentContext.lookup("persistence/dbunit");
LinkedList<String> categories = DataBase.getCategories(entityManager);
ListIterator<String> categoryIterator = categories.listIterator();
String category = "";
%>
<form action="category.jsp">
<% while (categoryIterator.hasNext()) { %>
<% category = categoryIterator.next(); %>
<input type="submit" class="submitButtonAsLink" value="<%= category %>" name="<%= category %>" /><br />
<% } %>
</form>
</body>
ItemEntity.java:
#Entity
public class ItemEntity implements Serializable {
private static final long serialVersionUID = 1L;
#Id #GeneratedValue(strategy = GenerationType.AUTO)
private String id;
private String title;
private String longDescription;
private double cost;
private String category;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
#Override
public int hashCode() {
int hash = 0;
hash += (id != null ? id.hashCode() : 0);
return hash;
}
#Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof ItemEntity)) {
return false;
}
ItemEntity other = (ItemEntity) object;
if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
return false;
}
return true;
}
#Override
public String toString() {
return "store.model.entities.ItemTable[ id=" + id + " ]";
}
//getters and setters omitted.
//There are getters and setters for every field except id.
}
Server Log:
INFO: file:/Users/griffgeorge/Dropbox/school/design-arch/labs/Lab4Exercise/build/web/WEB-INF/classes/_Lab4ExercisePU logout successful
INFO: Instantiated an instance of org.hibernate.validator.engine.resolver.JPATraversableResolver.
INFO: EclipseLink, version: Eclipse Persistence Services - 2.3.0.v20110604-r9504
INFO: file:/Users/griffgeorge/Dropbox/school/design-arch/labs/Lab4Exercise/build/web/WEB-INF/classes/_Lab4ExercisePU login successful
WARNING: Multiple [2] JMX MBeanServer instances exist, we will use the server at index [0] : [com.sun.enterprise.v3.admin.DynamicInterceptor#1ed957d].
WARNING: JMX MBeanServer in use: [com.sun.enterprise.v3.admin.DynamicInterceptor#1ed957d] from index [0]
WARNING: JMX MBeanServer in use: [com.sun.jmx.mbeanserver.JmxMBeanServer#1a84f3c] from index [1]
WARNING: PER01000: Got SQLException executing statement "CREATE TABLE ITEMENTITY (ID VARCHAR(255) NOT NULL, CATEGORY VARCHAR(255), COST FLOAT, LONGDESCRIPTION VARCHAR(255), TITLE VARCHAR(255), PRIMARY KEY (ID))": java.sql.SQLException: Table/View 'ITEMENTITY' already exists in Schema 'APP'.
WARNING: PER01000: Got SQLException executing statement "CREATE TABLE SEQUENCE (SEQ_NAME VARCHAR(50) NOT NULL, SEQ_COUNT DECIMAL(15), PRIMARY KEY (SEQ_NAME))": java.sql.SQLException: Table/View 'SEQUENCE' already exists in Schema 'APP'.
WARNING: PER01000: Got SQLException executing statement "INSERT INTO SEQUENCE(SEQ_NAME, SEQ_COUNT) values ('SEQ_GEN', 0)": java.sql.SQLIntegrityConstraintViolationException: The statement was aborted because it would have caused a duplicate key value in a unique or primary key constraint or unique index identified by 'SQL111012114449870' defined on 'SEQUENCE'.
INFO: WEB0671: Loading application [Lab4Exercise] at [/Lab4Exercise]
Your getCategories() method always returns an empty list, because the return in finally always runs (even after the first return).
You don't need a finally clause there at all. You can simplify to this
public static LinkedList<String> getCategories(EntityManager entityManager) {
try {
Query query = entityManager.createQuery(
"SELECT DISTINCT i.category from ItemEntity i");
return new LinkedList<String>(query.getResultList());
} catch(Exception e) {
System.out.println(e);
return new LinkedList<String>();
}
}
If your query.getResultList() is not empty, then it returns a non empty linked list of strings.
If your query.getResultList() is empty, then it returns an empty linked list of strings.
If an exception happens then it returns an empty list.
As you had before, it was always returning an empty list, even if your query was returning data.
To prove that the return in finally is the one that gets through, take a look at this
public class TestFinally {
public static void main(String[] args) {
System.out.println(TestFinally.test());
}
public static int test() {
try {
return 1;
} finally {
return 0;
}
}
}
returns
0
how about your persistence.xml? is that pointing to the datasource you expect? and then is that datasource pointing to the connection pool you expect?
We're running into a strange error using Oracle Odp.Net (connecting to Oracle 9). The problem is illustrated by the code snippet below.
This is the error we're experiencing:
ORA-00600: internal error code, arguments: [15419], [severe error during PL/SQL execution], [], [], [], [], [], []
ORA-06544: PL/SQL: internal error, arguments: [78502], [], [], [], [], [], [], []
ORA-06553: PLS-801: internal error [78502]
Googling around makes us suspect (though we're not entirely sure) that passing an array of Timestamps is not supported by Odp.Net.
So the question is 2-fold:
is it possible to pass an array of
timestamp to a pl/sql procedure using
odp.net?
if not, is there a good workaround available?
C# console program illustrating the problem:
using System;
using System.Collections;
using System.Data;
using Oracle.DataAccess.Client;
class Program
{
private const string _db = "<db>";
private const string _username = "<user>";
private const string _password = "<password>";
private const string _storedProcedureName = "<sproc>";
static void Main(string[] args)
{
var connectionString = string.Format(
"data source={0};user id={1};password={2}",
_db, _username, _password);
var connection = new OracleConnection(connectionString);
try
{
connection.Open();
var timeStamps = new[] { DateTime.Now, DateTime.Now };
var parameter = new OracleParameter("inTimeStamps", OracleDbType.TimeStamp)
{
Direction = ParameterDirection.Input,
CollectionType = OracleCollectionType.PLSQLAssociativeArray,
Size = timeStamps.Length,
Value = timeStamps
};
var command = connection.CreateCommand();
command.CommandType = CommandType.StoredProcedure;
command.CommandText = _storedProcedureName;
command.Parameters.Add(parameter);
command.ExecuteReader();
}
finally
{
connection.Close();
}
}
}
The code is calling the following PL/SQL stored procedure
TYPE ArrayOfTimestamps is table of timestamp index by binary_integer;
PROCEDURE TestOdpTimeStamp (inTimeStamps in ArrayOfTimestamps)
IS
test number;
BEGIN
select 1 into test from dual;
END;
You can pass a nested table of timestamps instead of an associative array to a PL/SQL procedure.
You need odp.net 11.1.0.6.20 or higher, you can connect with odp.net 11.1.0.6.20 to an Oracle 9 server.
Execute as Oracle user testts:
create or replace type MyTimeStamp as object
(
my timestamp
)
/
create or replace type mytimestamp_table as table of MyTimeStamp
/
create table testinserttimestamp
( my timestamp);
create or replace procedure test_timestamp_table (p_in in mytimestamp_table)
is
begin
for i in p_in.first..p_in.last loop
insert into testinserttimestamp values (p_in(i).my);
end loop;
commit;
end;
In C#, create a form with a button called button1, and do...
using System;
using System.Data;
using System.Windows.Forms;
using Oracle.DataAccess.Client;
using Oracle.DataAccess.Types;
namespace TestTimeStamp
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
public class MyUdtTimeStamp : INullable, IOracleCustomType
{
[OracleObjectMappingAttribute("MY")]
public OracleTimeStamp My { get; set; }
public bool IsNull
{
get { return false;}
}
public void FromCustomObject(OracleConnection con, IntPtr pUdt)
{
OracleUdt.SetValue(con, pUdt, "MY", My);
}
public void ToCustomObject(OracleConnection con, IntPtr pUdt)
{
My = (OracleTimeStamp)OracleUdt.GetValue(con, pUdt, "MY");
}
}
[OracleCustomTypeMappingAttribute("TESTTS.MYTIMESTAMP")]
public class StudentFactory : IOracleCustomTypeFactory
{
public IOracleCustomType CreateObject()
{
return new MyUdtTimeStamp();
}
}
[OracleCustomTypeMappingAttribute("TESTTS.MYTIMESTAMP_TABLE")]
public class PersonArrayFactory : IOracleArrayTypeFactory
{
public Array CreateArray(int numElems)
{
return new MyUdtTimeStamp[numElems];
}
public Array CreateStatusArray(int numElems)
{
return null;
}
}
private void button1_Click(object sender, EventArgs e)
{
OracleConnectionStringBuilder b = new OracleConnectionStringBuilder();
b.UserID = "testts";
b.Password = "ts";
b.DataSource = "ora11";
using (OracleConnection conn = new OracleConnection(b.ToString())) {
conn.Open();
using (OracleCommand comm = conn.CreateCommand())
{
comm.CommandText = "begin test_timestamp_table(:1); end;";
OracleParameter p = new OracleParameter();
p.OracleDbType = OracleDbType.Array;
p.Direction = ParameterDirection.Input;
p.UdtTypeName = "TESTTS.MYTIMESTAMP_TABLE";
MyUdtTimeStamp[] times = new MyUdtTimeStamp[2];
MyUdtTimeStamp m1 = new MyUdtTimeStamp();
m1.My = new OracleTimeStamp(DateTime.Now);
MyUdtTimeStamp m2 = new MyUdtTimeStamp();
m2.My = new OracleTimeStamp(DateTime.Now);
times[0] = m1;
times[1] = m2;
p.Value = times;
comm.Parameters.Add(p);
comm.ExecuteNonQuery();
}
conn.Close();
}
}
}
}
Do in Oracle...
SQL> select * from testinserttimestamp;
MY
-------------------------------------------------
12-10-09 21:13:54,328125
12-10-09 21:13:55,171875
There is a Metalink note (788282.1) that states that this is an error possible from passing an unsupported datatype. TIMESTAMP is not supported. You can get around it by constructing an anonymous PL/SQL block in your C# code and calling the problematic stored procedure from within that block.
EDIT:
I can't post the code from Metalink for obvious reasons.
The workaround is problematic if your array contains a lot of values, since the anonymous PL/SQL block will have to contain code to explicitly assign each entry in the array a value via a bind variable. It's clunky. This illustrates the idea:
comm.CommandText = "declare "+
"theTS mytimestamp_table;"+
"begin"+
" theTS(1):= :1;"+
" theTS(2):= :2;"+
" test_timestamp_table(theTS);"+
" end;";
You would then have to construct your parameter list to provide values for each of the bind variables.
I recently hit this problem too, but I overcome in a different way by using strings and to_timestamp, I hope this helps anyone who further down the line hits this problem:
http://timscyclingblog.wordpress.com/2011/10/07/oracle-plsqlassociativearray-timestamp-workaround/